zoukankan      html  css  js  c++  java
  • mybatis 使用sqlSessionFactory实现批量操作

    sqlSessionFactory实现批量提交的java,但无法返回受影响数量。

     1 public int updateBatch(List<Object> list){
     2         if(list ==null || list.size() <= 0){
     3             return -1;
     4         }
     5         SqlSessionFactory sqlSessionFactory = SpringContextUtil.getBean("sqlSessionFactory");
     6         SqlSession sqlSession = null;
     7         try {
     8             sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
     9             Mapper mapper = sqlSession.getMapper(Mapper.class);
    10             int batchCount = 1000;//提交数量,到达这个数量就提交
    11             for (int index = 0; index < list.size(); index++) {
    12                 Object obj = list.get(index);
    13                 mapper.updateInfo(obj);
    14                 if(index != 0 && index%batchCount == 0){
    15                     sqlSession.commit();
    16                 }                    
    17             }
    18             sqlSession.commit();
    19             return 0;
    20         }catch (Exception e){
    21             sqlSession.rollback();
    22             return -2;
    23         }finally {
    24             if(sqlSession != null){
    25                 sqlSession.close();
    26             }
    27         }
    28         
    29 }
    @Component
    public class SpringContextUtil implements ApplicationContextAware{
    
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringContextUtil.applicationContext = applicationContext;
        }
    
        public static ApplicationContext getApplicationContext(){
            return applicationContext;
        }
    
        public static Object getBean(Class T){
            try {
                return applicationContext.getBean(T);
            }catch (BeansException e){
                return null;
            }
        }
    
        public static Object getBean(String name){
            try {
                return applicationContext.getBean(name);
            }catch (BeansException e){
                return null;
            }
        }
    }
  • 相关阅读:
    学校重理论,公司重操作,计算机专业毕业生该何去何从?
    最简单的ajax示例
    几个简单的例子让你读懂什么是JAVA的堆栈跟踪
    避免在JSP中写java代码
    ==和equals()的区别
    测试,我误解了你
    项目管理十大TION法
    Web测试与APP测试有哪些异同?
    spring cglib 与 jdk 动态代理
    java.util.concurrent.Semaphore 使用
  • 原文地址:https://www.cnblogs.com/lgjava/p/11263035.html
Copyright © 2011-2022 走看看