1 mysql动态sql进行添加
<sql id="key">
<trim suffixOverrides=",">
</if><if test="s1!= null"> s1, </if>
<if test="s2!= null"> s2, </if>
<if test="s3!= null"> s3, </if>
<if test="s4!= null"> s4, </if>
create_time
<if test="s5!= null"> , s5, </if>
</trim>
</sql>
<sql id="value">
<trim suffixOverrides=",">
<if test="s1!= null"> #{s1}, </if>
<if test="s2!= null"> #{s2}, </if>
<if test="s3!= null"> #{s3}, </if>
<if test="s4!= null"> #{s4}, </if>
now()
<if test="s5!= null"> ,#{s5}, </if>
</trim>
</sql>
<insert id="ADD">
INSERT INTO table
(<include refid="key"></include>)
VALUES
(<include refid="value"></include>)
</insert>
这条动态sql就可以解决掉你在不知道前台传过来的数据情况下,完成添加功能,也可以为其中某些不需要前台添加的代码设置默认值。
查询动态sql
<select id="query" parameterType="int" resultType="map">
SELECT * FROM table
<where>
<if test="s1!=null">
s1= #{s1}
</if>
</where>
</select>
更新动态sql
<update id="update">
UPDATE table
<set>
<trim prefixOverrides="," suffixOverrides=",">
<if test="s1!= null"> s1= #{s1} , </if>
<if test="s2!= null"> s2= #{s2} , </if>
<if test="s3!= null"> s3= #{s3} , </if>
</trim>
</set>
</update>
现在问题来了,别人那些又好看有漂亮的博客是怎么写的啊啊啊啊啊啊啊啊啊啊啊啊啊啊!
今天发现一个bug,就是我在写修改的动态sql的时候,出现了数据库语法错误,每次都会在前面后者和面多凭借一个and或者逗号之类的。
<update id="DeleteQualityInfo">
UPDATE TB_CH_QUALITY SET LOGIC_DELETE = 1
<where>
<if test="ch_quality_id != null">
ch_quality_id = #{ch_quality_id}
</if>
</where>
</update>
<!--修改-->
<update id="update">
UPDATE table
<set>
<trim suffixOverrides="," prefixOverrides=",">
<if test="a!= null">
a= #{a}
</if>
<if test="b!= null">
, b= #{b}
</if>
<if test="c!= null">
, c= #{c}
</if>
<if test="d!= null">
, d= #{d}
</if>
<if test="e!= null">
, e= #{e}
</if>
<if test="f!= null">
, f= #{f}
</if>
<if test="g!= null">
, g= #{g}
</if>
<if test="h!= null">
, h= #{h}
</if>
</trim>
</set>
</update>
在前面加上一个<trim></trim>在trim中设置两个属性,一个
suffixOverrides
,一个
prefixOverrides
这两个标签会删除你动态sql拼接时候多余出来的and或者逗号。