MyBatis动态sql常用语法
在JDBC等其他操作数据库的框架中,对SQL语句的拼接和条件的判断时步骤非常的繁琐,而且出错率很高,有时候一个空格或是一个逗号的问题都会让程序直接报错,而MyBatis框架下的动态SQL可以比较方便的解决这个问题。
这里介绍一下我们常用的一些Mybatis动态SQL标签。
- if
- choose (when,otherwise)
- tirm (where,set)
- foreach
if
if表判断,假设,如果的意思,
在对SQL语句进行拼接的时候,我们通常会以数据是否为空作为能否拼接的判断,这里就会用到if语句
举个例子:
实体类及结果集的构造参看另一篇博客:Mybatis动态sql知识 :association和collection的区别
实现方法StudentMapper.xml中的代码如下:
<select id="getStuByClass" resultType="Student">
select *from student where classid=1
<if test="name!=null">
and name like concat(concat('%',#{name}),'%')
</if>
</select>
当满足if判断里面的条件时,则SQL语句拼接为:
select *from student where classid=1
and name like concat(concat('%',#{name}),'%')
我们将classid也作为一个if条件,则代码变为:
<select id="getStuByClass" resultType="Student">
select *from student where 1=1
<if test="classid!=null">
and classid=#{classid}
</if>
<if test="name!=null">
and name like concat(concat('%',#{name}),'%')
</if>
</select>
这里的where 1=1,是为了便于后面 if语句的拼接不出错。
- 当两个if语句都不写and时,if语句同时满足则SQL语句报错;
- 只第二个if语句写and时,当只有第二个if语句满足时,SQL语句报错
这个问题在后面的tirm标签可以较为方便地解决。
choose(when,otherwise)
类似于Java中的switch ,choose标签可以实现在多个SQL语句中依次判断,选择首次满足的SQL语句进行拼接,when类比于case,otherwise类比于defult。代码实例如下:
<select id="getStuByChoose" resultType="Student">
select *from student where 1=1
<choose>
<when test="name!=null">
and name like concat('%',#{name},'%')
</when>
<when test="age!=0">
and age>#{age}
</when>
<otherwise>
and classid=#{classid}
</otherwise>
</choose>
</select>
程序自上而下,当一个条件满足时,后序不再进行判断,例如:getStuByChoose(“张”,20,1);,则只会查找student表中所有名字中有“张”的学生,后两个条件并不起作用。
tirm (where,set)
之前在if语句时,为了让SQL语句的拼接不报错,我们在所有的if语句中的SQL语句前加上了and ,并在where后面添加了1=1,作为补充条件,不够灵活。
现在我们可以使用where标签解决这个问题,
<select id="getByClass" resultType="Student">
select *from student
<where>
<if test="classid!=null">
classid=#{classid}
</if>
<if test="name!=null and name!=''">
and name like concat(concat('%',#{name}),'%')
</if>
</where>
</select>
where标签拼接的SQL语句,如果是以and或or开头的,比如只有后一条判断满足时,where后直接跟上and,where标签可以自动的将这个and或or字段去除。
同样的,自定义tirm标签也拥有这种功能,并且应用面更加的广泛
tirm标签拥有四个子属性:prefix ,prefixOverrides ,suffix ,suffixOverrides。
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
prefixOverrides 属性会忽略通过管道分隔的文本序列(注意此例中的空格也是必要的)。它带来的结果就是所有在拼接的SQL语句前面含有 prefixOverrides 属性中指定的内容将被移除,并且插入 prefix 属性中指定的内容。
同样的,suffixOverrides会删除拼接的SQL语句中后面的指定的内容,换为suffix属性中的内容。代码实例如下:
<select id="getByClass" resultType="Student">
select *from student
<where>
<trim suffix="" suffixOverrides="and">
<if test="classid!=null">
classid=#{classid} and
</if>
<if test="name!=null and name!=''">
name like concat(concat('%',#{name}),'%')
</if>
</trim>
</where>
</select>
类似的还有用于update修改数据语句中的set标签,
set 元素会动态前置 SET 关键字,同时也会消除无关的逗号,因为用了条件语句之后很可能就会在生成的赋值语句的后面留下这些逗号。
<update id="update" parameterType="Student">
update student
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="relname!=null">
relname=#{relname},
</if>
<if test="sex!=null">
sex=#{sex},
</if>
<if test="age!=null">
age=#{age},
</if>
<if test="classid!=null">
classid=#{classid},
</if>
</set>
where id=#{id}
</update>
同样的,我们可以使用tirm标签来实现相同的功能。
<trim prefix="SET" suffixOverrides=",">
...
</trim>
foreach
foreach类似于Java中的for循环,我们可以对传入的数组,集合等数据集进行循环遍历,通常用于构建in条件语句,如:
<select id="getStuByArray" resultType="Student">
select *from student where classid in
<foreach collection="array" item="classid" open="(" separator="," close=")">
#{classid}
</foreach>
</select>
foreach的属性常用的有六个:collection ,item ,index , open ,close。
- collection:
要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用(“keyname”,keyname),以keyname作为键。 - item:集合中元素迭代时的别名,该参数为必选。
- index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
- open:foreach代码的开始符号,一般是(,和close=")"合用。常用在in(),values()时。该参数可选
- separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
- close: foreach代码的关闭符号,一般是),和open="("合用。常用在in(),values()时。该参数可选。
以传入Map类型的数据为例:
<select id="getStuByMap" resultType="Student">
select *from student where name like concat('%',#{name},'%') and classid in
<foreach collection="list" item="classid" open="(" separator="," close=")">
#{classid}
</foreach>
</select>
测试类:
//map键值对
public static void main(String[] args) {
SqlSession session = MybatisUtils.getSession();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name","张");
List list = new ArrayList();
list.add(1);
list.add(2);
map.put("list",list);
List<Student> slist = session.getMapper(StudentMapper.class).getStuByMap(map);
for (Student student : slist) {
System.out.println(student.getName()+"---"+student.getClassid());
}
}
输出结果: