Use MyBatis dynamic update data

  • 2020-05-17 05:39:12
  • OfStack

To write sql with mybatis, the object data needs to be updated dynamically. The fields that need to be updated are different each time. In order to prevent the null exception of null, dynamic sql needs to be used.


<update id="update" parameterType="com.commuli.po.User">
update s_user
<trim prefix="set" suffixOverrides=",">
<if test="name!=null">name=#{name},</if>
<if test="age!=null">age=#{age},</if>
<if test="address!=null">address=#{address},</if>
<if test="createDate!=null">createDate=#{createDate},</if>
</trim>
where
id=#{id}
</update>

Note: the trim tag is used to remove the comma ", "from the last field in sql.


Related articles: