问题:在项目中遇到需要同时更新字典表多个键的值,而字典表中多个键是由同一个字段保存的,问题就变成了如何根据同一个字段的不同属性更新对应的值,解决方法如下。
1.一次执行多条sql语句
需要在jdbc添加中allowMultiQueries=true
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
然后就可以在mapper映射文件中在同一个方法中写多条sql语句,多条sql语句中间用分号隔开
比如:
<update id="updateState">
update td_examinfo set exam_state=2 where now() > exam_examStartTime and exam_examEndTime > now();
update td_examinfo set exam_state=3 where now() > exam_examEndTime
</update>
经测试,方法的执行结果取决于多条sql执行结果的逻辑与,即有一条失败方法执行失败,但执行成功的并不会做回滚操作,所以这种方法不具备事务属性。
2.使用case when then end
<update id="updateValuesBykeys" parameterType="com.haha.TestDto">
UPDATE dict SET `value` = CASE
<if test="freeCount != null">
WHEN `key` = 'free_count' THEN #{freeCount}
</if>
<if test="rate != null">
WHEN `key` = 'rate' THEN #{rate}
</if>
<if test="singleMin != null">
WHEN `key` = 'single_min' THEN #{singleMin}
</if>
<if test="singleMax != null">
WHEN `key` = 'single_max' THEN #{singleMax}
</if>
<if test="freeCount != null or rate != null or singleMin != null or singleMax != null">
END
</if>
where `key` IN ('free_count','rate','single_min','single_max')
</update>