Mybatis的批量处理

1.配置文件

   jdbc.properties,需要注意,需要加allowMultiQueries=true配置

[html]  view plain  copy
  1. #MySql  
  2. jdbc.driverClassName=com.mysql.jdbc.Driver  
  3. jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/mybatis?useUnicode\=true&characterEncoding\=UTF-8&allowMultiQueries\=true  
  4. jdbc.username=root  
  5. jdbc.password=root  
 mybatis-config.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration  
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  5. <configuration>  
  6.     <properties resource="jdbc.properties"/>  
  7.     <typeAliases>  
  8.         <package name="com.mybatis.model"/>  
  9.     </typeAliases>  
  10.     <environments default="development">  
  11.         <environment id="development">  
  12.             <transactionManager type="JDBC" />  
  13.             <dataSource type="POOLED">  
  14.                 <property name="driver" value="${jdbc.driverClassName}" />  
  15.                 <property name="url" value="${jdbc.url}" />  
  16.                 <property name="username" value="${jdbc.username}" />  
  17.                 <property name="password" value="${jdbc.password}" />  
  18.             </dataSource>  
  19.         </environment>  
  20.         <environment id="test">  
  21.             <transactionManager type="JDBC" />  
  22.             <dataSource type="POOLED">  
  23.                 <property name="driver" value="${jdbc.driverClassName}" />  
  24.                 <property name="url" value="${jdbc.url}" />  
  25.                 <property name="username" value="${jdbc.username}" />  
  26.                 <property name="password" value="${jdbc.password}" />  
  27.             </dataSource>  
  28.         </environment>  
  29.     </environments>  
  30.     <mappers>  
  31.         <package name="com.mybatis.mappers"/>  
  32.     </mappers>  
  33. </configuration>  
2.接口Mapper:StudentMapper

[java]  view plain  copy
  1. import java.util.List;  
  2. import java.util.Map;  
  3.   
  4. import com.mybatis.model.Student;  
  5.   
  6. public interface StudentMapper {  
  7.     /** 
  8.      * 通过List集合批量插入 
  9.      * @param list 
  10.      * @return 
  11.      */  
  12.     public int batchInsertStudentWithList(List<Student> list);  
  13.     /** 
  14.      * 通过IdList进行Update特定字段为特定值 
  15.      * @param list 
  16.      * @return 
  17.      */  
  18.     public int batchUpdateByIdList(List<Integer> list);  
  19.     /** 
  20.      * 通过Map批量更新 
  21.      * @param map 
  22.      * @return 
  23.      */  
  24.     public int batchUpdateStudentWithMap(Map<String, Object> map);  
  25.     /** 
  26.      * 通过List集合批量更新 
  27.      * @param list 
  28.      * @return 
  29.      */  
  30.     public int batchUpdateStudentWithList(List<Student> list);  
  31.       
  32.     /** 
  33.      * 通过数组进行批量删除 
  34.      * @param array 
  35.      * @return 
  36.      */  
  37.     public int batchDeleteStudentWithArray(int array[]);  
  38.     /** 
  39.      * 能过IdList进行批量删除 
  40.      * @param list 
  41.      * @return 
  42.      */  
  43.     public int batchDeleteStudentWithIdList(List<Integer> list);  
  44.     /** 
  45.      * 通过list删除 
  46.      * @param list 
  47.      * @return 
  48.      */  
  49.     public int batchDeleteStudentWithList(List<Student> list);  
  50.     /** 
  51.      * 通过list中对象进行删除 
  52.      * @param list 
  53.      * @return 
  54.      */  
  55.     public int batchDeleteStudentWithListOnlyId(List<Student> list);  
  56. }  
3.Mapper配置StudentMapper

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper  
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  5. <mapper namespace="com.mybatis.mappers.StudentMapper">  
  6.   
  7.     <!-- 1,size:表示缓存cache中能容纳的最大元素数。默认是1024;   
  8.          2,flushInterval:定义缓存刷新周期,以毫秒计;   
  9.          3,eviction:定义缓存的移除机制;默认是LRU(least recently userd,最近最少使用),还有FIFO(first in   
  10.             first out,先进先出)   
  11.          4,readOnly:默认值是false,假如是true的话,缓存只能读。 -->  
  12.     <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false" />  
  13.   
  14.     <resultMap type="Student" id="StudentResult">  
  15.         <id property="id" column="id" />  
  16.         <result property="name" column="name" />  
  17.     </resultMap>  
  18.   
  19.     <delete id="batchDeleteStudentWithArray" parameterType="java.lang.String">  
  20.         DELETE FROM t_student where id in  
  21.         <foreach item="idItem" collection="array" open="(" separator=","  
  22.             close=")">  
  23.             #{idItem}  
  24.         </foreach>  
  25.     </delete>  
  26.       
  27.     <delete id="batchDeleteStudentWithIdList" parameterType="java.util.List">  
  28.         DELETE FROM t_student where id in  
  29.         <foreach collection="list" item="idItem" index="index" open="("  
  30.             separator="," close=")">  
  31.             #{idItem}  
  32.         </foreach>  
  33.     </delete>  
  34.       
  35.       
  36.     <delete id="batchDeleteStudentWithListOnlyId" parameterType="java.util.List">  
  37.         DELETE FROM t_student where id in  
  38.         <foreach collection="list" index="index" item="item" open="("    
  39.             separator="," close=")">    
  40.             #{item.id}    
  41.         </foreach>    
  42.     </delete>  
  43.       
  44.       
  45.     <!-- 效率低,不推荐 -->  
  46.     <delete id="batchDeleteStudentWithList" parameterType="java.util.List">  
  47.         <foreach collection="list" item="item" index="index" open="" close="" separator=";">  
  48.         DELETE  FROM t_student  
  49.             where id=#{item.id}  
  50.         </foreach>  
  51.     </delete>  
  52.       
  53.     <update id="batchUpdateByIdList" parameterType="java.util.List">  
  54.         UPDATE t_student set name='test' where id in  
  55.         <foreach collection="list" item="idItem" index="index" open="("  
  56.             separator="," close=")">  
  57.             #{idItem}  
  58.         </foreach>  
  59.     </update>  
  60.   
  61.     <update id="batchUpdateStudentWithList" parameterType="java.util.List">  
  62.         <foreach collection="list" item="item" index="index" open="" close="" separator=";">  
  63.         UPDATE t_student  
  64.             <set>  
  65.                 name=#{item.name}  
  66.             </set>  
  67.             where id=#{item.id}  
  68.         </foreach>  
  69.     </update>  
  70.   
  71.     <update id="batchUpdateStudentWithMap" parameterType="java.util.Map">  
  72.         UPDATE t_student SET name = #{name} WHERE id IN  
  73.         <foreach collection="idList" index="index" item="idItem" open="("  
  74.             separator="," close=")">  
  75.             #{idItem}  
  76.         </foreach>  
  77.     </update>  
  78.       
  79.     <insert id="batchInsertStudentWithList" parameterType="java.util.List">  
  80.         INSERT INTO /*+append_values */ t_student (name)  
  81.         VALUES  
  82.         <foreach collection="list" item="item" index="index" separator=",">  
  83.             (#{item.name})  
  84.         </foreach>  
  85.     </insert>  
  86. </mapper>   
 4.SqlSessionFactoryUtil
[java]  view plain  copy
  1. package com.mybatis.util;  
  2.   
  3. import java.io.InputStream;  
  4.   
  5. import org.apache.ibatis.io.Resources;  
  6. import org.apache.ibatis.session.SqlSession;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  9.   
  10. public class SqlSessionFactoryUtil {  
  11.   
  12.     private static SqlSessionFactory sqlSessionFactory;  
  13.       
  14.     public static SqlSessionFactory getSqlSessionFactory(){  
  15.         if(sqlSessionFactory==null){  
  16.             InputStream inputStream=null;  
  17.             try{  
  18.                 inputStream=Resources.getResourceAsStream("mybatis-config.xml");  
  19.                 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);  
  20.             }catch(Exception e){  
  21.                 e.printStackTrace();  
  22.             }  
  23.         }  
  24.         return sqlSessionFactory;  
  25.     }  
  26.       
  27.     public static SqlSession openSession(){  
  28.         return getSqlSessionFactory().openSession();  
  29.     }  
  30. }  
5.Model:Student
[java]  view plain  copy
  1. package com.mybatis.model;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Student implements Serializable {  
  6.   
  7.     private Integer id;  
  8.     private String name;  
  9.     private byte[] pic;// blob  
  10.     private String remark;// clob  
  11.     public Student() {  
  12.         super();  
  13.         // TODO Auto-generated constructor stub  
  14.     }  
  15.   
  16.     public Student(Integer id, String name) {  
  17.         super();  
  18.         this.id = id;  
  19.         this.name = name;  
  20.     }  
  21.   
  22.     public Student(String namee) {  
  23.         super();  
  24.         this.name = name;  
  25.     }  
  26.   
  27.     public Integer getId() {  
  28.         return id;  
  29.     }  
  30.   
  31.     public void setId(Integer id) {  
  32.         this.id = id;  
  33.     }  
  34.   
  35.     public String getName() {  
  36.         return name;  
  37.     }  
  38.   
  39.     public void setName(String name) {  
  40.         this.name = name;  
  41.     }  
  42.   
  43.     public byte[] getPic() {  
  44.         return pic;  
  45.     }  
  46.   
  47.     public void setPic(byte[] pic) {  
  48.         this.pic = pic;  
  49.     }  
  50.   
  51.     public String getRemark() {  
  52.         return remark;  
  53.     }  
  54.   
  55.     public void setRemark(String remark) {  
  56.         this.remark = remark;  
  57.     }  
  58.   
  59.     @Override  
  60.     public String toString() {  
  61.         return "Student [id=" + id + ", name=" + name + ", remark=" + remark + "]";  
  62.     }  
  63.   
  64. }  
6.测试类

[java]  view plain  copy
  1. package com.mybatis.service;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.apache.ibatis.session.SqlSession;  
  9. import org.apache.log4j.Logger;  
  10. import org.junit.After;  
  11. import org.junit.Before;  
  12. import org.junit.Test;  
  13.   
  14. import com.mybatis.mappers.StudentMapper;  
  15. import com.mybatis.model.Student;  
  16. import com.mybatis.util.SqlSessionFactoryUtil;  
  17.   
  18. public class StudentBatchTest {  
  19.   
  20.     private static Logger logger=Logger.getLogger(Student.class);  
  21.     private SqlSession sqlSession=null;  
  22.     private StudentMapper studentMapper=null;  
  23.       
  24.     /** 
  25.      * 测试方法前调用 
  26.      * @throws Exception 
  27.      */  
  28.     @Before  
  29.     public void setUp() throws Exception {  
  30.         sqlSession=SqlSessionFactoryUtil.openSession();  
  31.         studentMapper=sqlSession.getMapper(StudentMapper.class);  
  32.     }  
  33.   
  34.     /** 
  35.      * 测试方法后调用 
  36.      * @throws Exception 
  37.      */  
  38.     @After  
  39.     public void tearDown() throws Exception {  
  40.         sqlSession.close();  
  41.     }  
  42.       
  43.     //通过list进行批量插入  
  44.     @Test  
  45.     public void batchInsertStudentWithList(){  
  46.           List<Student> list= new ArrayList<Student>();  
  47.             for(int i = 2;i < 10;i++){  
  48.                 Student student = new Student();  
  49.                 student.setName("test" + i);  
  50.                 list.add(student);  
  51.             }  
  52.             int n=studentMapper.batchInsertStudentWithList(list);  
  53.             System.out.println("成功插入"+n+"条记录");  
  54.             sqlSession.commit();  
  55.     }  
  56.     //分页批量插入  
  57.     @Test  
  58.     public void batchInsertStudentPage(){  
  59.         List<Student> list= new ArrayList<Student>();  
  60.         for(int i = 0;i < 2000;i++){  
  61.             Student student = new Student();  
  62.             student.setName("test" + i);  
  63.             list.add(student);  
  64.         }  
  65.         try {  
  66.             save(list);  
  67.         } catch (Exception e) {  
  68.             e.printStackTrace();  
  69.         }  
  70.     }  
  71.       
  72.     private void save(List<Student> uidCodeList) throws Exception {  
  73.         SqlSession batchSqlSession = null;  
  74.         try {  
  75.             batchSqlSession =SqlSessionFactoryUtil.openSession();//获取批量方式的sqlsession          
  76.             int batchCount = 1000;//每批commit的个数  
  77.             int batchLastIndex = batchCount - 1;//每批最后一个的下标  
  78.             for(int index = 0; index < uidCodeList.size()-1;){  
  79.                 if(batchLastIndex > uidCodeList.size()-1){  
  80.                     batchLastIndex = uidCodeList.size() - 1;  
  81.                     batchSqlSession.insert("com.mybatis.mappers.StudentMapper.batchInsertStudentWithList", uidCodeList.subList(index, batchLastIndex+1));  
  82.                     batchSqlSession.commit();  
  83.                     System.out.println("index:"+index+"     batchLastIndex:"+batchLastIndex);  
  84.                     break;//数据插入完毕,退出循环  
  85.                       
  86.                 }else{  
  87.                     batchSqlSession.insert("com.mybatis.mappers.StudentMapper.batchInsertStudentWithList", uidCodeList.subList(index, batchLastIndex+1));                                   batchSqlSession.commit();  
  88.                     System.out.println("index:"+index+"     batchLastIndex:"+batchLastIndex);  
  89.                     index = batchLastIndex + 1;//设置下一批下标  
  90.                     batchLastIndex = index + (batchCount - 1);                        
  91.                 }                 
  92.             }                         
  93.         }finally{  
  94.             batchSqlSession.close();  
  95.         }         
  96.     }  
  97.     //通过IdList批量更新  
  98.     @Test  
  99.     public void batchUpdateByIdList() {  
  100.         logger.info("通过IdList批量更新");  
  101.         List<Integer> list = new ArrayList<Integer>();  
  102.         list.add(5);  
  103.         list.add(6);  
  104.         int n = studentMapper.batchUpdateByIdList(list);  
  105.         System.out.println("成功更新" + n + "条记录");  
  106.         sqlSession.commit();  
  107.     }  
  108.   
  109.     //通过map进行批量更新  
  110.     @Test  
  111.     public void batchUpdateStudentWithMap() {  
  112.         List<Integer> ls = new ArrayList<Integer>();  
  113.         for (int i = 5; i < 7; i++) {  
  114.             ls.add(i);  
  115.         }  
  116.         Map<String, Object> map = new HashMap<String, Object>();  
  117.         map.put("idList", ls);  
  118.         map.put("name""小群11");  
  119.         int n = studentMapper.batchUpdateStudentWithMap(map);  
  120.         System.out.println("成功更新" + n + "条记录");  
  121.         sqlSession.commit();  
  122.     }  
  123.     //通过list批量更新  
  124.     @Test  
  125.     public void batchUpdateStudentWithList() {  
  126.         logger.info("更新学生(带条件)");  
  127.         List<Student> list = new ArrayList<Student>();  
  128.         list.add(new Student(6"张三aa"));  
  129.         list.add(new Student(6"李四aa"));  
  130.         int n = studentMapper.batchUpdateStudentWithList(list);  
  131.         System.out.println("成功更新" + n + "条记录");  
  132.         sqlSession.commit();  
  133.     }  
  134.       
  135.     //通过Array进行批量删除  
  136.     @Test  
  137.     public void batchDeleteStudentWithArray() {  
  138.         logger.info("删除学生,通过Array");  
  139.         int array[] = new int[] { 34 };  
  140.         studentMapper.batchDeleteStudentWithArray(array);  
  141.         sqlSession.commit();  
  142.     }  
  143.     @Test  
  144.     public void batchDeleteStudentWithIdList() {  
  145.         logger.info("通过IdList批量更新");  
  146.         List<Integer> list = new ArrayList<Integer>();  
  147.         list.add(9);  
  148.         list.add(10);  
  149.         int n = studentMapper.batchDeleteStudentWithIdList(list);  
  150.         System.out.println("成功删除" + n + "条记录");  
  151.         sqlSession.commit();  
  152.     }  
  153.     @Test  
  154.     public void batchDeleteStudentWithList() {  
  155.         logger.info("通过IdList批量更新");  
  156.         List<Student> list = new ArrayList<Student>();  
  157.         list.add(new Student(12null));  
  158.         list.add(new Student(13null));  
  159.         int n = studentMapper.batchDeleteStudentWithList(list);  
  160.         System.out.println("成功删除" + n + "条记录");  
  161.         sqlSession.commit();  
  162.     }  
  163.       
  164.     @Test  
  165.     public void batchDeleteStudentWithListOnlyId() {  
  166.         logger.info("通过IdList批量更新");  
  167.         List<Student> list = new ArrayList<Student>();  
  168.         list.add(new Student(14null));  
  169.         list.add(new Student(15null));  
  170.         int n = studentMapper.batchDeleteStudentWithListOnlyId(list);  
  171.         System.out.println("成功删除" + n + "条记录");  
  172.         sqlSession.commit();  
  173.     }  
  174.       
  175. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值