如何在MyBatis的mapper.xml文件编写批量的修改的语句?
已知,dao 层提供的接口如下:
/**
* 批量修改用户
* @param userList
* @return
*/
public int updateUserBatch(List<User> userList);
批量修改的语句如下:
<!--
批量修改用户
当传入的是一个List,collection="list"
当传入的是一个数组,collection="array"
当传入的是包装类或者map,collection为包装类的属性或者map的key
注意:在mysql中,用多条语句运行的方式,需要在url连接中开启allowMultiQueries设置为true
-->
<update id="updateUserBatch" parameterType="list">
<foreach collection="list" item="user" separator=";">
UPDATE user
<set>
<if test="user.userName != null">
user_name = #{user.userName},
</if>
<if test="user.loginName != null">
login_name = #{user.loginName},
</if>
<if test="user.password != null">
password = #{user.password},
</if>
<if test="user.age != null">
age = #{user.age},
</if>
<if test="user.sex != null">
sex = #{user.sex},
</if>
<if test="user.deptId != null">
dept_id = #{user.deptId},
</if>
<if test="user.birthday != null">
birthday = #{user.birthday},
</if>
<if test="user.tvUpdate != null">
tv_update = #{user.tvUpdate},
</if>
</set>
WHERE user_id = #{user.userId}
</foreach>
</update>
最终拼接的语句类似如下的形式:
UPDATE user set xxx=xxx WHERE user_id = 1;
UPDATE user set xxx=xxx WHERE user_id = 2;
...
UPDATE user set xxx=xxx WHERE user_id = 144;
UPDATE user set xxx=xxx WHERE user_id = 145;
因为是要批量提交多条语句,所以需要在 mysql 的连接里面开启 allowMultiQueries=true
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&allowMultiQueries