MyBatis批量增删改的另外一种思路(推荐)

本文介绍了使用MyBatis进行批量操作的传统方式及其存在的问题,并提出了一种新的优化方案——利用JDBC底层的batch功能来替代传统的SQL拼接方法,以此提高效率并减少资源消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

零、传统拼接SQL语句的弊端

传统上利用Mybatis进行批量操作的方式本质来说是拼接SQL语句,然后交给底层执行,如之前博文而言。
其实这种方式是存在弊端的:
1. SQL语句可能会过长,DB的引擎可能不支持。
2. MyBatis拼接耗费资源不说还容易写错。

一、新思路

使用JDBC底层的batch进行批量操作
1. 先添加如下xml,注册一个batchSession
<!--
        单独配置一个执行JDBC批量操作的session,底层等于sqlSessionFactory.openSession(ExecutorType.BATCH); 
        底层使用org.apache.ibatis.executor.BatchExecutor作为执行引擎
-->
<bean id="batchSqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
    <constructor-arg index="1" value="BATCH"/>
</bean>
2. 使用注入
/** 注入批处理SqlSessionTemplate */
    @Autowired
    private SqlSessionTemplate batchSqlSessionTemplate;

    //这里的Transactionl一定要加,底层实现是命中SQL和Statement,必须使用的是同一个Connection
    /**
     * 批量 insert
     * @param models
     * @return
     */
    @Transactional
    public int batchcInsert(List<Model> models){
        int result = 0;
        BaseMapper<Model> modelMapper = (BaseMapper<Model>) batchSqlSessionTemplate.getMapper(mapperClass);
        for (Model model:models) {
            result += modelMapper.insert(model);
        }
        return result;
    }
    
    //这里的Transactionl一定要加,底层实现是命中SQL和Statement,必须使用的是同一个Connection
    /**
     * 批量update
     * @param models
     * @return
     */
    @Transactional
    public int batchcUpdate(List<Model> models){
        BaseMapper<Model> modelMapper = (BaseMapper<Model>) batchSqlSessionTemplate.getMapper(mapperClass);
        int result = 0;
        for (Model model:models) {
            result += modelMapper.update(model);
        }
        return result;
    }
    
    // 批量删除delete

 

转载于:https://www.cnblogs.com/LiuChunfu/p/7141795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值