Mybatis和Spring整合也是能用BatchExecutor的

  https://www.cnblogs.com/juniorMa/p/13930715.html

  这篇文章讨论了Mybatis和Spring整合后,batch不起作用,看来我有打脸了,写完了后我反复思考终于想通了,是我的测试方法有问题。

  因为我是循环执行的service里面的方法,这个方法是每次都会经过spring的事务提交的,如果把循环写在该事务方法里面还是能够使用batch方式的

@Transactional(propagation = Propagation.REQUIRED)
    public void addUser(User user) {
        
//        try {
//        ((UserServiceI) AopContext.currentProxy()).addUserScore();
//        }catch(Exception e) {
////            
//        }
        for (int i = 0;i<100;i++) {
            User userItem = new User();
            userItem.setUserId(String.valueOf(i));
//            user.setUserName("xdp_gacl_白虎神皇");
            userItem.setUserBirthday(new Date().toString());
            userItem.setUserSalary((double) (10 + i));
            userMapper.insert(userItem);
        }
        
//        int t = 1/0;
        
    }

  经过测试和跟代码,SqlSessionUtils.getSqlSession

public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {

    notNull(sessionFactory, "No SqlSessionFactory specified");
    notNull(executorType, "No ExecutorType specified");

    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);//不再是null了

    if (holder != null && holder.isSynchronizedWithTransaction()) {
      if (holder.getExecutorType() != executorType) {
        throw new TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction");
      }

      holder.requested();

      if (logger.isDebugEnabled()) {
        logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
      }

      return holder.getSqlSession();
    }

 import static org.mybatis.spring.SqlSessionUtils.getSqlSession;

  这样就能直接使用方法了,看来读源码能力有待提高

private class SqlSessionInterceptor implements InvocationHandler {
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      SqlSession sqlSession = getSqlSession(
          SqlSessionTemplate.this.sqlSessionFactory,
          SqlSessionTemplate.this.executorType,
          SqlSessionTemplate.this.exceptionTranslator);

 

posted on 2020-11-06 10:03  MaXianZhe  阅读(681)  评论(0编辑  收藏  举报

导航