Mybatis執(zhí)行多條語句/批量更新方式
Mybatis執(zhí)行多條語句/批量更新
Mybatis實現多條語句
通常用在刪除主表信息同時刪除子表信息。
如果利用多次Dao進行執(zhí)行sql,程序就寫起來麻煩并且閱讀難度會提升。
(刪除income表中的信息,同時刪除子表income_detail表中的相關信息)
delete from income_detail where income_id=#{id};? delete from income where id=#{id};
或者是批量更新,比如利用foreach批量update多條數據。
<update id="update"> ? ? <foreach collection="xxList" item="item" index="index" open="" close="" separator=";"> ? ? ? update t_xxx ? ? ? <set> ? ? ? ? xxx = #{item.xxx} ? ? ? </set> ? ? ? where id = #{item.id} ? ? </foreach> </update>
這些語句的類似點在于都是在mybatis中帶有分號的多條sql。
而直接執(zhí)行又會報錯,所以我們需要在jdbc連接中加上allowMultiQueries參數,設置為true。
<property name="url" value="jdbc:mysql://localhost:3306/amoeba?characterEncoding=UTF-8&allowMultiQueries=true"/>
jdbc.url=jdbc:mysql://localhost:3306/amoeba?characterEncoding=UTF-8&allowMultiQueries=true
Mybatis同時執(zhí)行多條語句
有個常見的場景:刪除用戶的時候需要先刪除用戶的外鍵關聯(lián)數據,否則會觸發(fā)規(guī)則報錯。
解決辦法不外乎有三個
- 1、多條sql分批執(zhí)行
- 2、存儲過程或函數調用
- 3、sql批量執(zhí)行
今天我要說的是MyBatis中如何一次執(zhí)行多條語句(使用mysql數據庫)。
1、修改數據庫連接參數加上allowMultiQueries=true,如:
hikariConfig.security.jdbcUrl=jdbc:mysql://xx.xx.xx:3306/xxxxx?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowMultiQueries=true
2、直接寫多條語句,用“;”隔開即可
<delete id="deleteUserById" parameterType="String"> ? ? delete from sec_user_role where userId=#{id}; ? ? delete from sec_user where id=#{id}; </delete>
僅此而已!?。?/p>
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring?Boot中KafkaListener的介紹、原理和使用方法案例詳解
本文介紹了Spring Boot中 @KafkaListener 注解的介紹、原理和使用方法,通過本文的介紹,我們希望讀者能夠更好地理解Spring Boot中 @KafkaListener 注解的使用方法,并在項目中更加靈活地應用2023-09-09springboot如何為web層添加統(tǒng)一請求前綴
這篇文章主要介紹了springboot如何為web層添加統(tǒng)一請求前綴,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02