mybatis判斷用insert還是update


下邊看一下mybatis的映射文件。

<insert id="AddTeacher" parameterType="com.mycompany.entity.Teacher">
<selectKey keyProperty="count" resultType="int" order="BEFORE">
select count(*) from Teacher where teacher_id = #{teacherId}
</selectKey>
<if test="count > 0">
update event
<set>
<if test="teacherName!= null" >
teacher_name= #{teacherName},
</if>
</set>
<where>
teacher_id = #{teacherId}
</where>
</if>
<if test="count==0">
insert into teacher(teacher_id,teacher_name) values (#{teacherId},#{teacherName})
</if>
</insert>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
可以看到mybatis的實現思路也是先查詢Id是否存在,在根據count判斷是insert還是update。

說明
1.實現原理是selectKey做第一次查詢,然后根據結果進行判斷,所以這里的order="BEFORE"是必須的,也是因BEFORE,所以沒法通過<bind>標簽來臨時存儲中間的值,只能在入參中增加屬性來存放。

2.就上面這個例子而言,就要求實體類中包含count屬性(可以是別的名字)。否則selectKey的結果沒法保存,如果入參是個Map類型,就沒有這個限制。

3.這種方式只是利用了selectKey會多執行一次查詢來實現的,但是如果你同時還需要通過selectKey獲取序列或者自增的id,就會麻煩很多(oracle麻煩,其他支持自增的還是很容易),例如我在上一篇中利用selectKey 獲取主鍵Id。

4.建議單獨查看學習一下selectKey的用法。
————————————————
版權聲明:本文為CSDN博主「老賊大魔王」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_36637705/article/details/78530442


免責聲明!

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



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