文章目录
本文章涉及环境版本:
- mysql 5.7
- Mybatis 3.5.x
- Maven 3.6.x
- JDK 1.8
项目代码仓库:
https://github.com/Gang-bb/Study-Record/tree/main/bzhan-mybatis-study
需要clone整个bzhan-mybatis-study项目
(整体是一个maven多module工程)
该文章对应:《bzhan-mybatis-study07 》module项目
1. 动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
2. 搭建环境
- 建表
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
准备一些测试数据:
- POJO类编写
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Blog {
private Integer id;
private String title;
private String author;
private Date createTime;
private Integer views;
}
- 编写dao层mapper接口和mapper.xml文件
3. IF语句使用
- BlogMapper
List<Blog> getBlogsIf(Map map);
- BlogMapper.xml
<select id="getBlogsIf" resultType="com.gangbb.model.pojo.Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
或者:(涉及where标签知识内容)
<select id="getBlogsIf" resultType="com.gangbb.model.pojo.Blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
- 测试类
@Test
public void getBlogs(){
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.openSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("author", "Gangbb");
List<Blog> blogList = blogMapper.getBlogsIf(map);
for (int i = 0; i < blogList.size(); i++) {
Blog blog = blogList.get(i);
System.out.println(blog);
}
} finally {
sqlSession.close();
}
}
4. choose (when, otherwise)语句使用
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
- BlogMapper
List<Blog> getBlogsChoose(Map map);
- BlogMapper.xml
<select id="getBlogsChoose" parameterType="map" resultType="com.gangbb.model.pojo.Blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
<otherwise>
views = 99999999
</otherwise>
</choose>
</where>
</select>
- 测试类
@Test
public void BlogChoose(){
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.openSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
//下面两个随意填入条件测试
//map.put("title", "学习如何找女朋友");
//map.put("author", "Gangbb");
List<Blog> blogList = blogMapper.getBlogsChoose(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
} finally {
sqlSession.close();
}
}
5. trim (where,set)语句使用
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
实例使用:
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
等价于:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
所谓的动态SQL,本质还是SQL语句 , 只是我们可以在SQL层面,去执行一个逻辑代码
6. SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用!
-
使用SQL标签抽取公共的部分
<sql id="if-title-author"> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
-
在需要使用的地方使用Include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <include refid="if-title-author"></include> </where> </select>
注意事项:
-
最好基于单表来定义SQL片段!
-
不要存在where标签
7. Foreach语句
- BlogMapper
List<Blog> getBlogsChoose(Map map);
- BlogMapper.xml
<!--
select * from mybatis.blog where 1=1 and (id=1 or id = 2 or id=3)
我们现在传递一个万能的map , 这map中可以存在一个集合!
-->
<select id="getBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
- 测试类
@Test
public void BlogForeach(){
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.openSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
map.put("ids", ids);
List<Blog> blogList = blogMapper.getBlogForeach(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
} finally {
sqlSession.close();
}
}
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
- 现在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!