MyBatis批量添加、修改和删除
废话不多说了,直接步入正题了。
1、批量添加元素session.insert(Stringstring,Objecto)
publicvoidbatchInsertStudent(){
List<Student>ls=newArrayList<Student>();
for(inti=5;i<8;i++){
Studentstudent=newStudent();
student.setId(i);
student.setName("maoyuanjun"+i);
student.setSex("man"+i);
student.setTel("tel"+i);
student.setAddress("浙江省"+i);
ls.add(student);
}
SqlSessionsession=SessionFactoryUtil.getSqlSessionFactory().openSession();
session.insert("mybatisdemo.domain.Student.batchInsertStudent",ls);
session.commit();
session.close();
}
<insertid="batchInsertStudent"parameterType="java.util.List">
INSERTINTOSTUDENT(id,name,sex,tel,address)
VALUES
<foreachcollection="list"item="item"index="index"separator=",">
(#{item.id},#{item.name},#{item.sex},#{item.tel},#{item.address})
</foreach>
</insert>
2、批量修改session.insert(Stringstring,Objecto)
实例1:
publicvoidbatchUpdateStudent(){
List<Integer>ls=newArrayList<Integer>();
for(inti=2;i<8;i++){
ls.add(i);
}
SqlSessionsession=SessionFactoryUtil.getSqlSessionFactory().openSession();
session.insert("mybatisdemo.domain.Student.batchUpdateStudent",ls);
session.commit();
session.close();
}
<updateid="batchUpdateStudent"parameterType="java.util.List">
UPDATESTUDENTSETname="5566"WHEREidIN
<foreachcollection="list"item="item"index="index"open="("separator=","close=")">
#{item}
</foreach>
</update>
实例2:
publicvoidbatchUpdateStudentWithMap(){
List<Integer>ls=newArrayList<Integer>();
for(inti=2;i<8;i++){
ls.add(i);
}
Map<String,Object>map=newHashMap<String,Object>();
map.put("idList",ls);
map.put("name","mmao789");
SqlSessionsession=SessionFactoryUtil.getSqlSessionFactory().openSession();
session.insert("mybatisdemo.domain.Student.batchUpdateStudentWithMap",map);
session.commit();
session.close();
}
<updateid="batchUpdateStudentWithMap"parameterType="java.util.Map">
UPDATESTUDENTSETname=#{name}WHEREidIN
<foreachcollection="idList"index="index"item="item"open="("separator=","close=")">
#{item}
</foreach>
</update>
3、批量删除session.delete(Stringstring,Objecto)
publicvoidbatchDeleteStudent(){
List<Integer>ls=newArrayList<Integer>();
for(inti=4;i<8;i++){
ls.add(i);
}
SqlSessionsession=SessionFactoryUtil.getSqlSessionFactory().openSession();
session.delete("mybatisdemo.domain.Student.batchDeleteStudent",ls);
session.commit();
session.close();
}
<deleteid="batchDeleteStudent"parameterType="java.util.List">
DELETEFROMSTUDENTWHEREidIN
<foreachcollection="list"index="index"item="item"open="("separator=","close=")">
#{item}
</foreach>
</delete>
好了,本文到此结束,希望对大家有所帮助。
热门推荐
2 祝福语简短的微信
10 物业小区高考祝福语简短
11 毕业教师花语祝福语简短
12 简短的祝福语中秋搞笑
13 爷爷庆生文案祝福语简短
14 新年祝福语简短又好听
15 妈妈的祝福语简短优美
16 朋友祝福语卡片简短大气
17 孩子新年祝福语简短精辟
18 对新人祝福语大全简短