1、批量添加元素session.insert(String string,object O)
public void batchInsertStudent(){ List<Student> ls = new ArrayList<Student>(); for(int i = 5;i < 8;i++){ Student student = new Student(); student.setId(i); student.setName("maoyuanjun" + i); student.setSex("man" + i); student.setTel("tel" + i); student.setAddress("浙江省" + i); ls.add(student); } SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession(); session.insert("mybatisdemo.domain.Student.batchInsertStudent", ls); session.commit(); session.close(); } <insert id="batchInsertStudent" parameterType="java.util.List"> INSERT INTO STUDENT (id,name,sex,tel,address) VALUES <foreach collection="list" item="item" index="index" separator="," > (#{item.id},#{item.name},#{item.sex},#{item.tel},#{item.address}) </foreach> </insert>
2、批量修改session. insert (String string,Object o)
1 实例1: 2 public void batchUpdateStudent(){ 3 List<Integer> ls = new ArrayList<Integer>(); 4 for(int i = 2;i < 8;i++){ 5 ls.add(i); 6 } 7 SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession(); 8 session.insert("mybatisdemo.domain.Student.batchUpdateStudent",ls); 9 session.commit(); 10 session.close(); 11 } 12 <update id="batchUpdateStudent" parameterType="java.util.List"> 13 UPDATE STUDENT SET name = "5566" WHERE id IN 14 <foreach collection="list" item="item" index="index" open="(" separator="," close=")" > 15 #{item} 16 </foreach> 17 </update> 18 19 实例2: 20 public void batchUpdateStudentWithMap(){ 21 List<Integer> ls = new ArrayList<Integer>(); 22 for(int i = 2;i < 8;i++){ 23 ls.add(i); 24 } 25 Map<String,Object> map = new HashMap<String,Object>(); 26 map.put("idList", ls); 27 map.put("name", "mmao789"); 28 SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession(); 29 session.insert("mybatisdemo.domain.Student.batchUpdateStudentWithMap",map); 30 session.commit(); 31 session.close(); 32 } 33 <update id="batchUpdateStudentWithMap" parameterType="java.util.Map" > 34 UPDATE STUDENT SET name = #{name} WHERE id IN 35 <foreach collection="idList" index="index" item="item" open="(" separator="," close=")"> 36 #{item} 37 </foreach> 38 </update>
3、批量删除session.delete(String string,Object o)