update
update元素
1. id : 与 Mapper接口对应的方法名称
2. parameterType : 传入的参数格式
3. flushCache : 是否清空缓存,默认为false
4. statementType : PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。
5. timeout : 等待数据库返回请求结果的秒数
1. 一般的update操作——返回值为更新的记录数目
mapper接口代码
/**
* 更新用户信息
* @param user
* @return 成功操作的记录数目
*/
int update(User user);
mapper.xml:
<update id = "update" parameterType = "User">
UPDATE USER SET user_name = #{userName},
pass_word = #{passWord},
WHERE ID = #{id};
</update>
2.update动态SQL语句
涉及到更新操作时,可能不需要对所有字段更新,这时不需要更新的字段需要保持原字段信息,因为不更新的字段,会被传递null到SQL中,引起异常。这时就需要进行动态SQL拼接,如下,使用trim就是为了删掉最后字段的“,”。
主要不用单独写SET了,因为set被包含在trim中了:
<update id="update" parameterType="user">
UPDATE user
<trim prefix="set" suffixOverrides=",">
<if test="userName!=null">user_name=#{userName},</if>
<if test="passWord!=null">pass_word=#{passWord},</if>
</trim>
WHERE id=#{id}
</update>
3. 更新过后得到更新的记录
平常我门都是更新数据,用更新的条件再查询一次,得到更新的记录。这样我门就进行了两次数据库操作,链接了两次数据库。增加了接口的处理事件,因为链接数据库是很耗时的操作。其实可以通过 mybatis 的 selectKey 标签来解决这个问题。
<update id="updateByUserName" parameterType="User">
<selectKey keyProperty='id' resultType='int' order='BEFORE'>
SELECT
(select id FROM user WHERE
user_name = #{userName}
)id
from DUAL
</selectKey>
UPDATE user SET
pass_word=#{passWord}
WHERE
user_name = #{userName}
</update>
4.批量修改
/**
* 批量更新用户信息
* @param user
* @return 成功操作的记录数目
*/
int update(List<User> list);
mapper.xml:
<update id="batchUpdate" parameterType="java.util.List">
update user
<trim prefix="set" suffixOverrides=",">
<trim prefix="user_name=case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.userName!=null">
when id=#{i.id} then #{i.userName}
</if>
</foreach>
</trim>
<trim prefix=" pass_word=case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.passWord!=null">
when id=#{i.id} then #{i.passWord}
</if>
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
<update id="batchUpdate" parameterType="java.util.Map" >
UPDATE USER SET status = #{status} WHERE id IN
<foreach collection="idList" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</update>
当值不同时,为了提高效率一般采用用case when来拼成一长串sql处理。