MERGE INTO用法:
meger into主要用在修改和增加操作中
大致意思是:判断一个条件,如果满足执行update,不满足执行insert
<update id="updateXxh" parameterType="java.util.Map" >
MERGE INTO table
USING dual ON (XXHID=#{xxhid})
WHEN MATCHED THEN
update set
BT = #{bt}
<if test="nd != null and nd != ''">,ND = #{nd}</if>
<if test="lc != null and lc != ''">,LC = #{lc}</if>
<if test="xxhnr != null and xxhnr != ''">,XXHNR = #{xxhnr}</if>
<if test="operatorid != null and operatorid != ''"> ,OPERATORID = #{operatorid}</if>
<if test="operator != null and operator != ''"> ,OPERATOR = #{operator}</if>
<if test="status != null and status != ''"> ,STATUS = #{status}</if>
where XXHID=#{xxhid}
WHEN NOT MATCHED THEN
insert
(
XXHID
<if test="bt != null and bt != ''">,BT </if>
<if test="nd != null and nd != ''">,ND </if>
<if test="lc != null and lc != ''">,LC </if>
<if test="xxhnr != null and xxhnr != ''">,XXHNR </if>
<if test="operatorid != null and operatorid != ''">,OPERATORID </if>
<if test="operator != null and operator != ''">,OPERATOR </if>
<if test="status != null and status != ''">,STATUS </if>
)
values(
#{xxhid}
<if test="bt != null and bt != ''">,#{bt}</if>
<if test="nd != null and nd != ''">,#{nd}</if>
<if test="lc != null and lc != ''">,#{lc}</if>
<if test="xxhnr != null and xxhnr != ''">,#{xxhnr}</if>
<if test="operatorid != null and operatorid != ''">,#{operatorid}</if>
<if test="operator != null and operator != ''">,#{operator}</if>
<if test="status != null and status != ''">,#{status}</if>
)
</update>
理解:
调用的时候会传入一个Map,这个map里面有一个键值对(键的值是:xxhid)。
程序执行到sql的时候,会把这个xxhid从map里面取出来,自动加上单引号拼接进去,执行sql
on后面的条件是查询的是table表中是否有xxhid这个值的XXHID键,如果有那就执行下面的update,
如果没有就执行insert操作。
注意:insert后面没有into!!!切记!
平常,我们写代码还可以在Java代码里面进行判断,是执行更新还是插入,但看到同事们的Java代码都是简简单单的调用,我就起了疑,所以学习了一下。