除了if与句之外,还有一些动态sql语法。
1、choose、when、otherwise
用xml配置:
<select id="queryNews" databaseId="mysql" resultMap="newsMapper">
select * from news_inf where status = 'ACTIVE'
<choose>
<when test="title != null">
and news_title regexp #{title}
</when>
<when test="content != null">
and news_content regexp #{content}
</when>
<otherwise>
and news_id in (select min(news_id) from news_inf where status = 'ACTIVE');
</otherwise>
</choose>
</select>
用注解和java配置:
SELECT("n.news_id as id" +
",n.news_title as title," +
"n.news_content as content," +
"n.status");
FROM("news_inf n");
WHERE("status = 'ACTIVE'");
if (title != null)
{
WHERE("news_title regexp #{title}");
}
else if (content != null)
{
WHERE("news_content regexp #{content}");
}
else
{
WHERE("news_id in (select min(news_id) from news_inf where status = 'ACTIVE')") ;
}
2、where、trim
sql中的where语句可以在MyBatis中的Mapper.xml中用where标签来完成,
这个标签最大的好处就是可以去除多余的and或者or。
<select id="queryNews" databaseId="mysql" resultMap="newsMapper">
select * from news_inf
<where>
<if test="title != null">
and news_title regexp #{title}
</if>
<if test="content != null">
and news_content regexp #{content}
</if>
</where>
</select>
而实际上where标签的功能是trim标签实现的.
<trim prefix="where" prefixOverrides="or|and">
<if test="title != null">
and news_title regexp #{title}
</if>
<if test="content != null">
and news_content regexp #{content}
</if>
</trim>
trim标签中有属性
prefix 和 suffix:其属性值分别对应于在这段sql语句(被trim标签包起来的sql语句)的前面或者后面添加的字符串值。
prefixOverrides 和 suffixOverrides:其属性值分别对应与要在这段sql语句中删除哪些不需要的内容。
3、set、trim
与where sql语句像似的是,在update中set语句也可能会多出",",为了方便去掉这个多余的逗号,可以用set标签代替直接写set到sql语句中
<update id="updateNews" databaseId="mysql" >
update news_inf
<set>
<if test="title != null">
news_title = #{title},
</if>
<if test="content != null">
news_content = #{content}
</if>
</set>
where news_id = #{oldId}
</update>
当然也可以用trim标签表示
<update id="updateNews" databaseId="mysql" >
update news_inf
<trim prefix="set" suffixOverrides=",">
<if test="title != null">
news_title = #{title},
</if>
<if test="content != null">
news_content = #{content}
</if>
</trim>
where news_id = #{oldId}
</update>
4、trim实现动态插入
当然trim还有一些其他灵活的用处,比如insert语句要插入出很多列,就可以去除可能多出来的“,”
<insert id="insertNews" databaseId="mysql" >
insert into news_inf (
<trim suffixOverrides=",">
<if test="title != null">
news_title,
</if>
<if test="content != null">
news_content,
</if>
<if test="status != null">
status
</if>
</trim>
) values (
<trim suffixOverrides=",">
<if test="title != null">
#{title},
</if>
<if test="content != null">
#{content},
</if>
<if test="status != null">
#{status}
</if>
</trim>
)
</insert>
本文深入探讨了MyBatis框架中的动态SQL语法,包括choose、when、otherwise、where、trim、set等标签的使用技巧,以及如何通过这些标签解决SQL语句中常见的冗余问题,如去除多余的AND、OR或逗号。
2034

被折叠的 条评论
为什么被折叠?



