MyBatis动态SQL的学习心得
1、if元素
相当于JAVA中的if语句。常常和test属性联合使用,有如下查询要求
1>当name不为空时,执行模糊查询。如下代码清单:
<select id="selData" parameterType="string" resultType="com.test.Data">
select * from data
where 1=1
<if test=" name!=null and name!='' ">
and name like concat('%',#{name},'%')
</if>
</select>
2、choose when otherwise元素
相当于JAVA中的switch…case…default…语句,假设有一个这样的场景:
1>如果id不为空,则用id进行查询
2>如果id为空,name不为空,则用name作为条件进行模糊查询
3>如果id,name都为空,则查询所有性别代号为1的
代码如下:
<select id="getData" parameterType="com.test.user" resultType="com.test.user">
select *
from user
where 1=1
<choose>
<when test="id!=null and id!=''">
and id=#{id}
</when>
<when test="name!=null and name!=''">
and name like concat('%',#{name},'%')
</when>
<otherwise>
and age = 1
</otherwise>
</choose>
</select>
3、trim where set 元素
大家会发现,以上sql中条件都会加“1=1”,这是为了避免sql语句不报错,好奇心强的可以试试!,当然也可以不写“1=1”,那sql语句就如下写法:
<select id="getData" parameterType="string" resultType="com.test.user">
select * from user
<where>
<if test=" name!=null and name!='' ">
and name like concat('%',#{name},'%')
</if>
</where>
</select>
当where里面的条件成立时,才会组装到sql语句中,当然有时候也会去掉一些特殊的字符,比如:and、or,使用trim元素可以实现,如下代码清单:
<select id="getData" parameterType="string" resultType="com.test.user">
select * from user
<trim prefix="where" prefixOverrides="and">
<if test=" name!=null and name!='' ">
and name like concat('%',#{name},'%')
</if>
</trim>
</select>
注:prefix代表的是语句的前缀,prefixOverrides代表的是需要去掉的前缀字符串,该写法基本上是与where等效的。
数据更新,如果user表中有一个主键,两个字段,如果更新字段不在同一时间,那么就得写两条sql,如果字段多的话,那就更费时间了!set可以很好地解决这个问题,如下代码清单:
<update id="getData" parameterType="string">
update user
<set>
<if test=" name!=null and name!='' ">
name = #{name},
</if>
<if test=" age!=null and age!='' ">
age= #{age},
</if>
</set>
where id=#{id}
</update>
当然也可以这样:
......
<trim prefix="set" suffixOverrides=",">
......
</trim>
......
4、foreach元素
foreach是一个循环语句,它的作用是遍历集合,可支持List,数组,Set,往往用于in、save等。有如下查询需求:
1>根据一个角色编号的List查询数据信息,代码如下:
<select id="getDataList" parameterType="list" resultType="com.test.user">
select *
from user
where id in
<foreach item="id" collection="ids" index="index" open="(" separator="," close=")">
#{id}
</foreach>
</select>
item表示当前对象元素
collection表示mapper层的参数名称…@param(“ids”)…
index表示索引
open和close表示用什么符号将这些数据包装起来
separator表示每一个元素之间的分割符号
注:对于大量数据的in语句要视情况用,否则会影响效率!
5、bind元素
bind元素的作用是通过OGNL表达式去自定义一个上下文变量,方便使用,在mysql中,使用concat即可将%和参数连接起来。而oracle则不行,oracle需要用“||”连接。就需要提供两种方式的sql,可移植性低,bind则完美的解决了这个问题。
1>比如按name模糊查询
public user getData(@param("name")String name);
<select id="getData" parameterType="string" resultType="com.test.user">
<bind name="pattern_name" value="'%'+ name +'%'"></bind>
select *
from user
where name like #{pattern_name}
</select>
希望以上对大家写牛叉的sql提供帮助,谢谢!
本内容为《Java EE互联网轻量级框架整合开发》学习所得,如有雷同,望见谅!