mybatis批量插入、批量更新

批量新增:

@Autowired

private SqlSessionTemplate sqlSessionTemplate;

SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
try
{
    for(int i=0; i< size; i++) {
        session.insert("com.test.mapper.TestMapper.insertSelective", testList.get(i));

        boolean ifCommit = (i > 0 && i % 1000 == 0) || i == size - 1;
        if (ifCommit) {
            // 手动每1000个一提交,提交后无法回滚
            session.commit();
            // 清理缓存,防止溢出
            session.clearCache();
        }
    }
} catch (Exception e) {
    // 没有提交的数据可以回滚
    session.rollback();
    LOGGER.error("batch insert test error: " + e);
} finally {
    session.close();

}


批量更新:

url配置中增加:allowMultiQueries=true

   
        update test_info set test3 = test3 + #{item.test3}
        where test1 = #{item.test1} AND test2 = #{item.test2}
   


你可能感兴趣的:(mybatis)