mybatis@insert?注解如何判斷insert或是update
@insert注解判斷insert或update
最近參與研發(fā)了一個項目,需要用到mybatis,和我之前接觸的不同,我們的sql語句并沒有寫在xml中,而是使用的注解。
所以在此做個筆記方便以后查找。
@insert 注解
簡單的就不多說主要是有個業(yè)務(wù)需求,當一條數(shù)據(jù)存在時update ,不存在時insert,這時就會用到 ON DUPLICATE KEY UPDATE
其中appserverid 和 userid 是主鍵
@Insert({
?? ??? ?"INSERT INTO KZT_APPSERVER_HISTORY(APPSERVERID,USERID) values(#{appid},#{userid})",
? ? ? ?"ON DUPLICATE KEY UPDATE `TIMES` = `TIMES`+1 ",
?? ??? ?})
?? ?int addHistory(@Param("userid") String userid,@Param("appid") String appid);實現(xiàn)insert Or update的操作
在工作過程中 我們會經(jīng)常遇到 saveOrUpdate這種情況 而Mbatis中并沒有提供這樣的操作
在這里 我們通過selectKey 這個標簽來實現(xiàn)saveOrUpdate
selectKey的作用是在mybatis框架中,在插入到表格之后或者之前,查詢主鍵的值。
selectKey有以下幾個屬性
resultType:返回的主鍵的類型keyPropety:實體類對應(yīng)的主鍵的屬性。order:如果是after,那么先插入,在執(zhí)行selectKey中的sql。如果是before,則反之。
從上面的屬性中我們可以明確 可以在插入前先查 然后進行if else 判斷 從而實現(xiàn)saveOrUpdate 列出一段代碼實例以供參考
其中 order="BEFORE" 尤為關(guān)鍵
<insert id="insertStat" parameterType="com.thd2000.freela.domain.Stat">
<selectKey keyProperty="statId" resultType="int" order="BEFORE">
select count(*) FROM tb_stat
<include refid="Where_Clause" />
</selectKey>
<if test="statId == 0">
insert into tb_stat
(
stat_type,
stat_key,
stat_num,
create_time,
update_time,
stat_type_key,
stat_type_usertype,
stat_type_userid,
stat_type_planid
)
values
(
#{statType},
#{statKey},
#{statNum},
NOW(),
NOW(),
#{statTypeKey},
#{statTypeUserType},
#{statTypeUserId,jdbcType=VARCHAR},
#{statTypePlanId,jdbcType=VARCHAR}
)
</if>
<if test="statId > 0">
update tb_stat set stat_num=stat_num+#{statNum},update_time=NOW()
<include refid="Where_Clause" />
</if>
</insert>以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring MVC獲取參數(shù)和自定義參數(shù)類型轉(zhuǎn)換器及編碼過濾器
這篇文章主要為大家詳細介紹了Spring MVC獲取參數(shù)和自定義參數(shù)類型轉(zhuǎn)換器及編碼過濾器,文中通過代碼示例介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下2023-06-06
SpringMVC如何獲取表單數(shù)據(jù)(radio和checkbox)
這篇文章主要介紹了SpringMVC如何獲取表單數(shù)據(jù)(radio和checkbox)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
JDK21新特性Record?Patterns記錄模式詳解(最新推薦)
這篇文章主要介紹了JDK21新特性Record?Patterns記錄模式詳解,本JEP建立在Pattern?Matching?for?instanceof(JEP?394)的基礎(chǔ)上,該功能已在JDK?16中發(fā)布,它與Pattern?Matching?for?switch(JEP?441)共同演進,需要的朋友可以參考下2023-09-09
SpringBoot業(yè)務(wù)邏輯異常的處理方法介紹
本篇文章為大家展示了如何在SpringBoot中統(tǒng)一處理邏輯異常,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲2022-09-09
SpringBoot3實現(xiàn)webclient的通用方法詳解
Spring Boot WebClient 是 Spring Framework 5 中引入的一個新的響應(yīng)式 Web 客戶端,用于異步和響應(yīng)式地與外部服務(wù)進行通信,下面我們就來看看SpringBoot3實現(xiàn)webclient的通用方法吧2024-04-04
MyBatis傳入List集合查詢數(shù)據(jù)問題
這篇文章主要介紹了MyBatis傳入List集合查詢數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

