介绍:
什么是动态SQL:
动态Sql指的是根据不同的查询条件,生成不同的sql语句
我们之前写的sql语句都是比较简单的,如果有比较复杂的业务,我们需要写复杂的sql语句,往往需要拼接sql,但是容易由于符号的引用错误
mybatis的动态sql语句就是用来解决这个问题的通过if where choose when otherwise trim set foreach 等标签可以组合成非常灵活的sql语句
<if>:
先看一个需求:根据作者名字和博客名字来查询博客,如果作者名字为空,那么只根据博客名字查询,反之根据作者名字来查询
1.编写接口类:
List<Blog> queryBolgif(Map map);
2.编写Sql语句:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog where
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</select>
3.测试:
@Test
public void testQueryBlogIf(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title","如此简单");
map.put("author","赫于富");
List<Blog> blogs = mapper.queryBlogIf(map);
System.out.println(blogs);
session.close();
}
如果author为空,那么查询语句是: select * from blog where title=#{title}
但是如果title为空呢? 那么查询语句是: select * from blog where and author=#{author} 这样就报错了,这是一个错误的语句
如何解决? 一般if 都是配合where一起使用:
<where>
用 where 节点将所有的查询条件包起来,如果有满足的条件,where 节点会自动加上,如果没有,where 节点也将不存在,在有满足条件的情况下,where 还会自动处理 and 关键字。
所以将sql语句改为如下:
<select id="selectIf" parameterType="map" resultType="com.kuang.pojo.Bolg">
select * from vueblog
<where>
<if test="title !=null">
title=#{}
</if>
<if test="auther!=null">
and auther=#{author}
</if>
</where>
</select>
<foreach>一般用来处理数组/集合
需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息
1.编写接口:
List<Blog> queryBolgForeach(Map map);
2.编写sql语句:
<select id="" resultType="Blog">
select * from vueblog where id in
<foreach collection="array" open="(" close=")" item="id" separator=",">
#{id}
</foreach>
</select>
collection:表示数组变量
open:表示循环结束后左边的符号
close:表示循环结束后右边的符号
item:表示循环时候的单个变量
separator:表示循环的元素之间的分隔符
注意: 默认情况下,无论我的数组和集合参数名字叫什么,在xml访问的时候,都是array,我们可以通过@Param注解给参数重新制定名字
Integer batchInsertUser(@Param("users") List<User> users);
<insert id="batchInsertUser">
insert into user (username,address) values
<foreach collection="users" separator="," item="user">
(#{user.username},#{user.address})
</foreach>
</insert>
<set>
set关键字一般在更新中使用,更新的字段可能不确定,如果对象中存在该字段的值,就更新该字段,不存在就不更新
需求:更新一个用户的信息
Integer updateUser(User user);
<update id="updateUser" parameterType="org.hyf.mybatis.model.User">
update user
<set>
<if test="username!=null">
username=#{username},
</if>
<if test="address!=null">
address=#{address},
</if>
</set>
where id = #{id}
</update>
<choose>
有时候我们不想用所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,类似于Java中的switch语句
1.编写接口方法
List<Blog> queryBlogChoose(Map map);
2.sql文件
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title!=null>
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
<otherwise>
</choose>
</where>
</select>