Mybatis batch模式批量执行(插入)

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    //通过Mybatis batch模式批量插入群组人员
    //开启BATCH批量模式
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    TIdReGroupUserMapper tIdReGroupUserMapper = sqlSession.getMapper(TIdReGroupUserMapper.class);
    int addNum = 0;
    try {
            TIdReGroupUser tIdReGroupUser = new TIdReGroupUser();
            for (int i = 0; i < userIds.length; i++) {
                tIdReGroupUser.setId(UUID.randomUUID().toString());
                tIdReGroupUser.setGroupId(groupId);
                tIdReGroupUser.setUserId(userIds[i]);
                addNum += tIdReGroupUserMapper.insert(tIdReGroupUser);
            }
            sqlSession.commit();
        }finally {
            closeSqlSession(sqlSession, sqlSessionFactory);
        }

可以通过增加一个计数来达到每多少次时开始commit

    /**
     * 每多少次时开始commit
     */
    private static final int batchCountToSubmit = 100;
    //计数
    int batchLastIndexToSubmit = 0;
    放在for循环里,到达总数就提交,记得最后也提交一次
    
posted @ 2022-07-27 14:19  Ideaway  阅读(1486)  评论(0)    收藏  举报