MyBatis批量增刪改的另外一種思路(推薦)


零、傳統拼接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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM