动态操作这里使用到了标签
trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略),可以完成set或者是where标记的功能。标签的四个主要的属性:
- prefix:前缀覆盖并增加其内容
- suffix:后缀覆盖并增加其内容
- prefixOverrides:前缀判断的条件
- suffixOverrides:后缀判断的条件
新增
<insert id="saveDynamicCow" useGeneratedKeys="true" keyProperty="intCowId">
insert into cowtest
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="intPastureId != null and '' != intPastureId">
intPastureId,
</if>
<if test="varCowCode != null and '' != varCowCode">
varCowCode,
</if>
<if test="cSex != null and '' != cSex">
cSex,
</if>
<if test="addSource != null and '' != addSource">
addSource,
</if>
<if test="sireClass != null and '' != sireClass">
sireClass,
</if>
<if test="dateLeave != null and '' != dateLeave">
dateLeave,
</if>
<if test="intLeaveClass != null and '' != intLeaveClass">
intLeaveClass,
</if>
<if test="intReason != null and '' != intReason">
intReason,
</if>
<if test="intCurBar != null and '' != intCurBar">
intCurBar,
</if>
<if test="intCurBarName != null and '' != intCurBarName">
intCurBarName,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="intPastureId != null and '' != intPastureId">
#{intPastureId},
</if>
<if test="varCowCode != null and '' != varCowCode">
#{varCowCode},
</if>
<if test="cSex != null and '' != cSex">
#{cSex},
</if>
<if test="addSource != null and '' != addSource">
#{addSource},
</if>
<if test="sireClass != null and '' != sireClass">
#{sireClass},
</if>
<if test="dateLeave != null and '' != dateLeave">
#{dateLeave},
</if>
<if test="intLeaveClass != null and '' != intLeaveClass">
#{intLeaveClass},
</if>
<if test="intReason != null and '' != intReason">
#{intReason},
</if>
<if test="intCurBar != null and '' != intCurBar">
#{intCurBar},
</if>
<if test="intCurBarName != null and '' != intCurBarName">
#{intCurBarName},
</if>
</trim>
</insert>
这里会忽略最后的逗号“,”
修改
<update id="updateDynamicCow">
update cowtest
<trim prefix="SET" suffixOverrides=",">
<if test="dateBirthDate != null and '' != dateBirthDate">
dateBirthDate= #{dateBirthDate},
</if>
<if test="decBirWeight != null and '' != decBirWeight">
decBirWeight= #{decBirWeight},
</if>
<if test="decQuotiety != null and '' != decQuotiety">
decQuotiety= #{decQuotiety},
</if>
<if test="intCurBar != null and '' != intCurBar">
intCurBar= #{intCurBar},
</if>
<if test="intCurBarName != null and '' != intCurBarName">
intCurBarName= #{intCurBarName},
</if>
<if test="intCurFetal != null and '' != intCurFetal">
intCurFetal= #{intCurFetal},
</if>
<if test="intBreed != null and '' != intBreed">
intBreed= #{intBreed},
</if>
<if test="cSex != null and '' != cSex">
cSex= #{cSex},
</if>
</trim>
where varCowCode= #{varCowCode}
</update>
此外
trim标签还可以在where语句中省略前缀and,当然我们也可以使用 where 1=1 后面再跟上判断语句
更多用法参考: mybatis标签之——trim