Mybatis动态sql

MyBatis的动态SQL是基于OGNL表达式的它可以帮助我们方便的在SQL语句中实现某些逻辑

MyBatis中用于实现动态SQL的元素主要有

If

Choose(when,otherwise)

Trim

Where

Set

Foreach

1、 if

if用于简单的条件判断

<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">

select * from t_blog where 1=1;

<if test="title != null">

and title =#{title}

</if>

</select>

如果没有title参数则查询所有的blog,如果有title参数则查询的结果必须满足title =#{title}.

2、 choose

choose元素的作用就相当于JAVA中的switch语句,通常都是whenotherwise搭配的

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">

select * from t_blog where 1=1

<choose>

<when test="title !=null">

and title = #{title}

</when>

<when test="content !=null">

and content = #{content}

</when>

<otherwise>

and owner = "owner1"

</otherwise>

</choose>

</select>

when中的条件满足时就输出其中的内容,按照条件的顺序,当when中只要有条件满足的时候就会跳出choose,即所有的whenotherwise条件中只有一个会输出条件都不满足时,输出otherwise中的内容

 

foreach

foreach的主要用在构建in条件中它可以在SQL语句中进行迭代一个集合。Foreach元素的主要属性有item,index,collection,open,sperator,close. Item表示集合中每一个元素进行迭代时的别名index指定一个名字用于表示在迭代过程中每次迭代到的位置open表示语句以什么开始separator表示在每次进行迭代之间以什符号作为分隔符close表示以什么结束。Collection属性必须是指定的但在不同情况下该属性的值是不一样的主要有以下3种情况:

1如果传入的是单参数且参数类型是一个List的时候,collection的属性值为list

2如果传入的是单参数且参数类型是一个array数组的时候collection的属性值为array

3如果传入的参数是多个的时候我们就要把他们封装成一个Map

<select id="dynamicForeachTest"  resultType="Blog">

select * from t_blog where title like "%"#{title}"%"

and id in

<foreach collection="ids" item="item">

#{item}

</foreach>

</select>

示例collections的值为ids,是传入的参数Mapkey。

3、 where

where元素的作用是会在写入where元素的地方输出一个where。如果输 

出后是and开头的mybatis会把第一个and忽略

<select id="dynamicWhereTest" parameterType="Blog"

resultType="Blog">

select * from t_blog

<where>

<if test="title != null">

title=#{title}

</if>

<if test="content != null">

and content = #{content}

</if>

</where>

</select>

4set

set元素主要是用在更新操作的时候它的主要功能和where元素差不多主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把逗号忽略如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段

<update id="dynamicSetTest" parameterType="Blog">

update t_blog

<set>

<if test="title != null">

title=#{title},

</if>

<if test="content != null">

and content = #{content},

</if>

<if test="owner != null">

or owner = #{owner}

</if>

</set>

where id = #{id}

</update>

上述代码中,如果set中一个条件都不满足,即set中包含的内容为空的时候就会报错。

6trim

trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverides;

<select id="dynamicTrimTest" resultType="Blog">

select * from t_blog

<trim prefix="where" prefixOverrides="and|or">

<if test="title != null">

title=#{title}

</if>

<if test="content != null">

and content = #{content}

</if>

<if test="owner != null">

or owner = #{owner}

</if>

</trim>

</select>