隐藏

Mybatis中的update动态SQL语句

发布:2021/7/29 10:05:25作者:管理员 来源:本站 浏览次数:769



Mybatis中的CRUD操作(增删改查)中,简单的SQL操作比较直观,如查找操作:


<select id="findBySrcId" resultMap="entityRelationResultMap">

 SELECT * FROM ENTITY_RELATION WHERE SRC_ID=#{srcId}

</select>


其中id对应同名java文件中的方法,resultMap对应的自定义的数据类型(当使用java自带类型就更容易了,比如java.lang.String之类的)。


但是涉及到更新操作时,可能不需要对所有字段更新,这时不需要更新的字段需要保持原字段信息,当使用以下信息就会报错:


<update id="updateOne"  parameterType="com.inspur.search.data.EntityRelation">

update ENTITY_RELATION SET SRC_ID=#{srcId},SRC_TYPE=#{srcType},DEST_ID=#{destId},

       DEST_TYPE=#{destType},REL_TYPE=#{relType},STATUS=#{status},SN_ID=#{snId}

where id=#{id}

</update>


因为不更新的字段,会被传递null到SQL中,引起异常。


这时就需要进行动态SQL拼接,如下,使用trim就是为了删掉最后字段的“,”。

主要不用单独写SET了,因为set被包含在trim中了:


<update id="updateOne"  parameterType="com.inspur.search.data.EntityRelation">

UPDATE ENTITY_RELATION

<trim prefix="set" suffixOverrides=",">

 <if test="srcId!=null">SRC_ID=#{srcId},</if>

 <if test="srcType!=null">SRC_TYPE=#{srcType},</if>

 <if test="destId!=null">DEST_ID=#{destId},</if>

 <if test="destType!=null">DEST_TYPE=#{destType},</if>

 <if test="relType!=null">REL_TYPE=#{relType},</if>

 <if test="status!=null">STATUS=#{status},</if>

 <if test="snId!=null">SN_ID=#{snId},</if>

</trim>

WHERE id=#{id}

</update>