什么是动态SQL:
简介:
MyBatis 的强大特性之一便是它的动态 SQL
如果你有使用 JDBC 或其它类似框架的经验,你 就能体会到根据不同条件拼接 SQL 语句的痛苦:
where id=1 and name=“zhangsan” and password=“123456”
insert into user(id,name,value) values(1,”zhangsna”,”123456)
update user set name=”zhangsan2”,password=”123” where id=1
动态sql元素和 JSTL标签类似;
复杂的SQL语句,往往需要拼接。而拼接SQL稍微不注意,由于引号,空格等的缺失可能都会导致错误。
解决办法:
使用MyBatis的动态SQL,通过if
where,set,trim
foreach
choose,when,otherwise
等标签,可以组合成非常灵活的SQL语句,从而在提高SQL语句的准确性的同时,也大大提高了开发人员的效率。
新建一个数据库表:blog
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1.创建一个maven基础工程
2.IDutils工具类
使用UUID创建唯一id
IDUtils:
public class IDUtils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
3.实体类的编写
Blog:
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
4.编写Mapper接口及xml文件
BlogMapper:
public interface BlogMapper {
}
BlogMapper.xml:
<mapper namespace="com.kuang.dao.BlogMapper">
mapper>
5.mybatis核心配置文件,下划线命名 驼峰命名自动转换
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<mappers>
<mapper class="com.kuang.dao.BlogMapper"/>
mappers>
6.初始化接口数据
编写接口:
//新增一个博客
int addBlog(Blog blog);
Mapper.xml:
<insert id="addBlog" parameterType="Blog">
insert into mybatis.blog (id,title,author,create_time,views)
values (#{id},#{title},#{author},#{createTime},#{views});
insert>
test:初始化博客数据
@Test
public void addInitBlog(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtils.getId());
blog.setTitle("Mybatis如此简单");
blog.setAuthor("狂神说");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("Java如此简单");
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("Spring如此简单");
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("微服务如此简单");
mapper.addBlog(blog);
session.commit();
session.close();
}
应用场景:
根据条件append查询条件,拼接SQL
需求:根据作者名字author和博客名字title来查询博客:
1.编写接口类:
//需求1
List<Blog> queryBlogIf(Map map);
2.编写Mapper.xml中SQL语句
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from `blog` where
<if test="author!=null">
author=#{author}
if>
<if test="title!=null">
and title=#{title}
if>
select>
3.测试
@Test
public void test(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
map.put("author","狂神说");
map.put("title","Mybatis如此简单");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
session.close();
}
问题:
当author为null,title不为空时,select语句为:select * from blog where and title=#{title}
,这是错误的SQL语句。如何解决呢?采用下面where标签;
应用场景:
修改上面的SQL语句:
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from `blog`
<where>
<if test="author!=null">
author=#{author}
</if>
<if test="title!=null">
and title=#{title}
</if>
</where>
</select>
应用场景:
,
剔除update blog set author=#{author},
编写Mapper.xml中SQL语句
<update id="updateBlog" parameterType="map">
update `blog`
<set>
<if test="author!=null">
author=#{author},
if>
<if test="title!=null">
title=#{title}
if>
set>
where id=#{id}
update>
应用场景:
select * from blog where id in (1,2,3,4)
**1.编写接口类:
List<Blog> queryBlogForeach(Map map);
2.编写Mapper.xml中SQL语句
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="idList" item="id" open="(" close=")" separator="or">
id=#{id}
foreach>
where>
select>
3.测试
@Test
public void test(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
List<String> idList=new ArrayList<String>();
idList.add("ae52b845132a4a7190d4c3e192265fd2");
map.put("idList",idList); //List是map的一个属性
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
session.commit();
session.close();
}
应用场景:
1.编写接口类:
List<Blog> queryBlogChoose(Map map);
2.编写Mapper.xml中SQL语句
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="author!=null">
author=#{author}
when>
<when test="title!=null">
title=#{title}
when>
<otherwise>
and views=#{views}
otherwise>
choose>
where>
select>
3.测试
@Test
public void test(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
map.put("title","Java如此简单2");
map.put("author","狂神说2");
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
session.commit();
session.close();
}
有时候可能某个sql语句我们用的特别多,为了增加代码的复用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
提取SQL片段:
<sql id="if-title-author">
<if test="author!=null">
author=#{author}
if>
<if test="title!=null">
and title=#{title}
if>
sql>
引用SQL片段:
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from `blog`
<where>
<include refid="if-title-author"/>
where>
select>
注意:
动态SQL小结: