批量的saveOrupdate:
<!--批量的插入 or 更新的操作-->
<insert id="batchInsertStaff">
insert into xxxTable (
merchant_id, app_id, department_id,
`name`, mobile, token,
created_at, updated_at)
values
<foreach collection="list" item="staff" separator="," >
(
#{merchantId,jdbcType=INTEGER},#{appId,jdbcType=INTEGER},#{staff.departmentId},
#{staff.name},#{staff.mobile},#{staff.token},
NOW(),NOW()
)
</foreach>
on duplicate key update department_id = values(department_id),updated_at = values(updated_at)
</insert>
單條的saveOrupdate:
1.根據selectkey判斷查詢的count值是否爲1,然後再進行新增或更新
<insert id="insertOrUpdateOneUserInfo">
<selectKey keyProperty="count" resultType="int" order="BEFORE">
select count(*) as count from `${tableName}` where userid = #{user.userid}
</selectKey>
<!-- 如果大於0則更新 -->
<if test="count>0">
UPDATE `${tableName}`
<set >
<if test="user.appId != null" >
`app_id` = #{user.appId},
</if>
<if test="user.yunid != null" >
`yunid` = #{user.yunid},
</if>
<if test="user.qr_scene != null" >
`qr_scene` = #{user.qr_scene},
</if>
<if test="user.openid != null" >
`openid` = #{user.openid},
</if>
<if test="user.qr_scene_str != null" >
`qr_scene_str` = #{user.qr_scene_str},
</if>
<if test="user.nickname != null" >
`nickname` = #{user.nickname},
</if>
<if test="user.language != null" >
`language` = #{user.language},
</if>
<if test="user.city != null" >
`city` = #{user.city},
</if>
<if test="user.country != null" >
`country` = #{user.country},
</if>
<if test="user.remark != null" >
`remark` = #{user.remark},
</if>
<if test="user.headimgurl != null" >
`headimgurl` = #{user.headimgurl},
</if>
<if test="user.province != null" >
`province` = #{user.province},
</if>
<if test="user.tagIdList != null" >
`tagid_list` = #{user.tagIdList},
</if>
<if test="user.subscribe_scene != null" >
`subscribe_scene` = #{user.subscribe_scene},
</if>
<if test="user.unionid != null" >
`unionid` = #{user.unionid},
</if>
<if test="user.subscribe != null" >
`subscribe` = #{user.subscribe},
</if>
<if test="user.groupid != null" >
`groupid` = #{user.groupid},
</if>
<if test="user.subTime != null" >
`subscribe_time` = #{user.subTime},
</if>
<if test="user.sexStr != null" >
`sex` = #{user.sexStr},
</if>
<if test="user.updatedAt != null" >
`updated_at` = #{user.updatedAt},
</if>
</set>
WHERE userid = #{user.userid}
</if>
<!-- 如果等於0則保存 -->
<if test="count==0">
INSERT IGNORE INTO `${tableName}`
(
<include refid="wx_temp_params" />
)
values
(
#{user.appId},#{user.yunid},#{user.userid},#{user.point},#{user.qr_scene},
#{user.openid},#{user.qr_scene_str},#{user.nickname},#{user.language},#{user.city},
#{user.country},#{user.remark},#{user.headimgurl},#{user.province},#{user.tagIdList},
#{user.subscribe_scene},#{user.unionid},#{user.subscribe},#{user.groupid},#{user.subTime},
#{user.sexStr},#{user.createdAt},#{user.updatedAt}
)
</if>
</insert>
2.根據相應的唯一主鍵來判斷是否新增或更新 [對事務支持較好]
INSERT INTO
user(userid,sex,age)
VALUES('oCCtTxOz28457LUISKyOq4r94DYE','男',18)
ON DUPLICATE KEY UPDATE sex=VALUES(sex),age=VALUES(age)