mybatis批量 *** 作

mybatis批量 *** 作,第1张

mybatis批量 *** 作

批量 *** 作普通的可以使用foreach标签拼一下sql就行了,但是量多的,拼sql就不太合适了

foreach拼sql

使用这种方式需要在jdbc驱动链接里加上&allowMultiQueries=true参数,可以在sql语句后携带分号,实现多语句执行。同时可以执行批处理,同时发出多个SQL语句。

Integer updateShopNames(@Param("shopMemberIntentions") List shopMemberIntentions);

    
        update shop_member_intention set shop_name = #{item.shopName},shop_simple_name = #{item.shopSimpleName}, gmt_modified = gmt_modified where id = #{item.id}
    

sqlSessionFactory批量提交
@Autowired
private SqlSessionFactory sqlSessionFactory;
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
    ShopMemberIntentionMapper mapper = sqlSession.getMapper(ShopMemberIntentionMapper.class);
    for (int i = 0; i < shopMemberIntentions.size(); i++) {
        mapper.updateShopName(shopMemberIntentions.get(i));
        if(i % 200 == 0){
            sqlSession.flushStatements();
        }
    }

    sqlSession.flushStatements();
    sqlSession.commit();
}catch (Exception e) {
    log.error("supplementShopName() called with parameters => , exception = 【{}】", e.getMessage());
    sqlSession.rollback();
}finally {
    sqlSession.close();
}

如果方法上用了@Transactional注解,由于在 Spring 集成的情况下,事务连接由 Spring 管理(SpringManagedTransaction),所以这里不需要手动关闭 sqlSession,在这里手动提交(commit)或者回滚(rollback)也是无效的。如果没有使用事务注解,那就一步一步来,提交了再关闭。

批量提交只能应用于 insert, update, delete。
并且在批量提交使用时,如果在 *** 作同一SQL时中间插入了其他数据库 *** 作,就会让批量提交方式变成普通的执行方式,所以在使用批量提交时,要控制好 SQL 执行顺序。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5582732.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存