MyBatis中动态insert和update

2018-06-22  本文已影响0人  修远路

最近在用Mybatis写一些插入和修改的sql很费力,想着能不能偷懒,结果还真有,以下皆来自互联网:

Insert

<insert id="addVideo" parameterType="com.test.model.Video">

INSERT INTO tb_video

<trim prefix="(" suffix=")" suffixOverrides=",">

video_id, ah,

<if test="isApply != null">is_apply,</if>

<if test="applyRemark != null and applyRemark !=''">apply_remark,</if>

<if test="checkRemark != null and checkRemark !=''">check_remark,</if>

<if test="isDelete != null">is_delete,</if>

<if test="optionStatus != null">option_status,</if>

<if test="checkUser != null and checkUser !=''">check_user,</if>

<if test="applyUser != null and applyUser !=''">apply_user,</if>

</trim>

<trim prefix="values (" suffix=")" suffixOverrides="," >

#{videoId}, #{caseNo},

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

<if test="applyRemark != null and applyRemark !=''">#{applyRemark},</if>

<if test="checkRemark != null and checkRemark !=''">#{checkRemark},</if>

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

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

<if test="checkUser != null and checkUser !=''">#{checkUser},</if>

<if test="applyUser != null and applyUser !=''">#{applyUser},</if>

</trim>

</insert>

update

<update id="updVideoByVideoId" parameterType="com.test.model.Video">

UPDATE tb_video

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

<if test="isApply != null">is_apply=#{isApply},</if>

<if test="isDelete != null"> is_delete=#{isDelete},</if>

<if test="applyRemark != null and applyRemark !=''"> apply_remark=#{applyRemark},</if>

<if test="checkRemark != null and checkRemark !=''"> check_remark=#{checkRemark},</if>

<if test="optionStatus != null"> option_status=#{optionStatus},</if>

<if test="checkUser != null and checkUser !=''"> check_user=#{checkUser},</if>

<if test="applyUser != null and applyUser !=''"> apply_user=#{applyUser},</if>

</trim>

WHERE video_id =#{videoId}

</update>

注:

1.trim标签的属性

prefix:前缀覆盖并增加其内容。也就是给中的sql语句加上前缀;

suffix:后缀覆盖并增加其内容。给包裹的sql语句加上后缀;

prefixOverrides:前缀判断的条件。取消指定的前缀,如where;

suffixOverrides:后缀判断的条件。取消指定的后缀,如and | or.,逗号等。

2.Video的属性isApply/isDelete/optionStatus均是Integer,所以if标签里去除isApply != ''判断;其他属性是String。

上一篇 下一篇

猜你喜欢

热点阅读