Java-Mybatis-04-动态SQL、标签、缓存
学习视频:B站 狂神说Java – https://www.bilibili.com/video/BV1NE411Q7Nx
学习资料:mybatis 参考文档 – https://mybatis.org/mybatis-3/zh/index.html
1、动态SQL环境搭建
动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
1.1、搭建环境:
创建数据库:
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
创建一个基础工程:
- 导包
- 编写配置文件
- 编写实体类
- 编写实体类对应的 Mapper接口 和Mapper.xml文件
编写实体类:
Blog实体类和数据库中的 blog 中进行 ORM映射。
package com.AL.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime; // 属性名和字段名不一致
private int views;
}
编写工具类:在实体类中,需要一个唯一的 ID 的工具类,即生成一堆随机数 去作为独一无二的 id。 在工具类中创建 IDutils 类,使用UUID,可以去生成唯一的名字 ID。
package com.AL.utils;
import org.junit.Test;
import java.util.UUID;
public class IDutils {
public static String getID(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test(){
System.out.println(IDutils.getID());
System.out.println(IDutils.getID());
System.out.println(IDutils.getID());
}
}
创建好实体类后,在我们这里,java的实体类中的属性和 数据库中的字段名不一致。 如:
private Date createTime; //java中 pojo中的 属性
`create_time` DATETIME NOT NULL COMMENT '创建时间', #数据库表中的字段
为了使java中的变量名字 属性名 和 数据库表格的字段保持一致, 需要允许辨别 大小写的存在。 那么可以在mybatis-config.xml核心配置文件中 去开启 自动驼峰命名规则。如下所示
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--XML 配置文件或者预先定义的一个 config,去SqlSessionFactoryBuilder, 配置数据库,便于创建sqlSessionFactory实例-->
<configuration>
<!--引入外部配置文件-->
<properties resource="db.properties">
<!-- 在 db.properties 属性配置文件中定义了这些 sql 配置,可以不在这里的xml配置文件中定义。
如果定义的话, 会以 xml资源配置文件中的 (引入外部配置文件) 为基准,优先级比较高
<property name="username" value="root"/>
<property name="pwd" value="111"/>
-->
</properties>
<settings>
<!-- 日志工厂实现-->
<setting name="logImpl" value="LOG4J"/>
<!-- 是否开启自动驼峰命名规则(camel case)映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&charsetEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--关联映射文件-->
<mappers>
<!-- <mapper resource="com.AL.dao.BlogMapper"/>-->
<mapper class="com.AL.dao.BlogMapper"/>
</mappers>
</configuration>
数据库配置文件:db.properties
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8
username = root
password = 123456
编写接口 mapper文件:操作数据库元素的方法接口:
package com.AL.dao;
import com.AL.pojo.Blog;
public interface BlogMapper {
// 插入数据
int addBlog(Blog blog);
}
编写接口实现类:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace= 绑定一个对应的Dao/Mapper接口
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
-->
<mapper namespace="com.AL.dao.BlogMapper">
<!--select 查询语句 -->
<insert id="addBlog" parameterType="blog">
insert into mybatis.blog(id, title, author, create_time, views)
values(#{id},#{title},#{author},#{createTime},#{views});
</insert>
</mapper>
工具类:用于能够创建 SqlSession 实例对象的:
package com.AL.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
//import javax.annotation.Resources;
// sqlSessionFactory --> sqlSession
public class MybatisUtils {
// 创建这个sqlSessionFactory,是从资源文件resource中的去获得。
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//利用mybatis第一步: 获取一个sqlSessionFactory对象
String resource = "mybatis-config.xml";
/** 注意:不需要修改,是因为导入的包不正确.不是 import javax.annotation.Resources
* 将ResourcesgetResourceAsStream(resource);改为
* Resources.class.getResourceAsStream(resource);
* //得到配置文件流
* InputStream inputStream = Resources.class.getResourceAsStream(resource);
*/
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
//有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession() {
//SqlSession sqlSession = sqlSessionFactory.openSession();
//return sqlSession;
return sqlSessionFactory.openSession();
}
}
注意:在这里的 Resources 的导入包为 import org.apache.ibatis.io.Resources; 我导入了 import javax.annotation.Resources 这个是关于获取注解资源的包。否则就会出错。如下所示: 这其实也表明了这个包应该使用的是:org.apache
测试:查看能够完成插入语句:
package com.AL.dao;
import com.AL.pojo.Blog;
import com.AL.utils.IDutils;
import com.AL.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class MyTest {
@Test
public void addInitBlog() {
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getID());
blog.setTitle("520");
blog.setAuthor("xinxin");
blog.setCreateTime(new Date());
blog.setViews(999);
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();
}
}
查看结果:表明此时搭建的环境没有问题。
[com.AL.dao.BlogMapper.addBlog]-==> Preparing: insert into mybatis.blog(id, title, author, create_time, views) values(?,?,?,?,?);
[com.AL.dao.BlogMapper.addBlog]-==> Parameters: 0d6edee5a1be4fda8265ccc18b938e27(String), 520(String), xinxin(String), 2021-05-20 11:16:52.798(Timestamp), 999(Integer)
1.2、动态SQL之IF语句
需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
1.编写接口:mapper 文件,定义操作数据库的接口方法
package com.AL.dao;
import com.AL.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
// 插入数据
int addBlog(Blog blog);
// 查询博客
List<Blog> queryBlogIF(Map map);
}
2.接口实现类:mapper.xml文件,实现接口方法,sql语句:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace= 绑定一个对应的Dao/Mapper接口
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
-->
<mapper namespace="com.AL.dao.BlogMapper">
<!--select 查询语句 -->
<insert id="addBlog" parameterType="com.AL.pojo.Blog">
insert into mybatis.blog(id, title, author, create_time, views)
values(#{id},#{title},#{author},#{createTime},#{views});
</insert>
<select id="queryBlogIF" parameterType="map" resultType="com.AL.pojo.Blog">
-- select * from mybatis.blog where 1=1;
select * from mybatis.blog
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
</mapper>
3.测试
- 没有给定参数的时候的测试:
- 给定参数的时候的测试方法:map.put(“title”, “520”);
- 给定author 名字 或者两者都给定的情况下: map.put(“author”, “xinxin”);
package com.AL.dao;
import com.AL.pojo.Blog;
import com.AL.utils.IDutils;
import com.AL.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class MyTest {
@Test
public void addInitBlog() {
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getID());
blog.setTitle("520");
blog.setAuthor("xinxin");
blog.setCreateTime(new Date());
blog.setViews(999);
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();
}
@Test
public void queryBlogIF(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// 给定参数的情况下测试
map.put("title", "520");
map.put("author", "xinxin");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
}
这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from blog where title=#{title},但是如果title为空呢?那么查询语句为 select * from blog where and author=#{author},这是错误的 SQL 语句。
如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:
SELECT * FROM BLOG
WHERE
这个问题不能简单地用条件元素来解决。如何解决呢?请看下面的 where 语句!
1.3、动态SQL常用标签
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
trim(where、set)
**使用where标签,进行连接判断sql语句:**对于上述查询出现错误的时候,使用 where 语句进行修改。
<select id="queryBlogIF" parameterType="map" resultType="com.AL.pojo.Blog">
-- select * from mybatis.blog where 1=1;
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
此时结果能够正常查询:
[com.AL.dao.BlogMapper.queryBlogIF]-==> Preparing: -- select * from mybatis.blog where 1=1; select * from mybatis.blog WHERE title = ? and author = ?
[com.AL.dao.BlogMapper.queryBlogIF]-==> Parameters: 520(String), xinxin(String)
[com.AL.dao.BlogMapper.queryBlogIF]-<== Total: 0
where 标签 只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 标签也会将它们去除。
choose、when、otherwise
choose例子: choose (when, otherwise)
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。
针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。还是上面的例子,但是策略变为:
- 传入了 “title” 就按 “title” 查找,
- 传入了 “author” 就按 “author” 查找的情形。
- 若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。
1.接口:
List<Blog> queryBlogChoose(Map map);
2.接口实现类:mapper.xml文件中对sql语句的修改:
<select id="queryBlogIF" parameterType="map" resultType="com.AL.pojo.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>
3.测试:对此方法中进行不同的注释 ,参数传递 去观察结果:
@Test
public void queryBlogIFChooseTest(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// 给定参数的情况下测试
map.put("title", "520");
map.put("author", "xinxin");
map.put("views", 9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
System.out.println(blogs);
}
结果: 结果可以发现,choose选择了 title这个满足的条件,执行这个。尽管它有999 views。
[com.AL.dao.BlogMapper.queryBlogIF]-==> Preparing: select * from blog WHERE title = ?
[com.AL.dao.BlogMapper.queryBlogIF]-==> Parameters: 520(String)
[com.AL.dao.BlogMapper.queryBlogIF]-<== Total: 1
从结果中可以发现:只要前面某一个满足了, 就不会执行后面的。
trim、where、set
set标签
类似的用于 动态更新语句的解决方案叫做 set。 set 元素可以用于动态包含需要更新的列,忽略其它不需要更新的列。
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
来看看与 set 元素等价的自定义 trim 元素吧:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
注意,我们覆盖了后缀值设置,并且自定义了前缀值。
set标签例子:
编写接口文件: 更新博客和查询博客。都采用了 map 键值对映射的方式去输入 blog 属性的信息。
public interface BlogMapper {
// 插入数据
int addBlog(Blog blog);
// 查询博客
List<Blog> queryBlogIF(Map map);
List<Blog> queryBlogChoose(Map map);
// 更新博客
int updateBlog(Map map);
}
mapper.xml文件,接口实现类:在 set 标签中的语句要使用 逗号隔开,前面几个标签都没有使用隔开符号。
<!--注意set是用的逗号隔开-->
<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>
测试:
@Test
public void updateBlog(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
//map.put("title","动态SQL");
map.put("author","xinxin");
//map.put("id","ae5a839239804cac8aad4f163990dd28");
mapper.updateBlog(map);
session.close();
}
所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码.
1.4、SQL片段
所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码.
有的时候,我们可能会将一些功能的部分抽取出来,方便服用。
SQL片段: 可以引用sql片段,去进行sql实现
**提取SQL片段:**使用sql标签抽取公共的部分
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
**引用SQL片段:**在需要的地方使用 Include 标签引用即可。
<select id="queryBlogIf" parameterType="map" resultType="com.AL.pojo.Blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>
注意:
①、最好基于 单表来定义 sql 片段,提高片段的可重用性
②**、在 sql 片段中不要存在 where**
接口:
List<Blog> queryBlogIFInclude(Map map);
mapper.xml文件修改:
<!-- 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="queryBlogIFInclude" parameterType="map" resultType="com.AL.pojo.Blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>
测试:
@Test
public void queryBlogIFInclude(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// 给定参数的情况下测试
map.put("title", "520");
map.put("author", "xinxin");
//map.put("views", 999);
List<Blog> blogs = mapper.queryBlogIFInclude(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
System.out.println(blogs);
}
foreach
foreach:
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
<where>
<foreach item="item" index="index" collection="list"
open="ID in (" separator="," close=")" nullable="true">
#{item}
</foreach>
</where>
</select>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你 指定 开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
例子:
1、编写接口mapper: 我们手动将数据库中前三个数据的id修改为1,2,3;
// 查询 blog 表中 id 分别为1,2,3的博客信息
List<Blog> queryBlogForeach(Map map);
2、编写SQL语句: 在这里我们相当于是传递一个万能的 map, 且 map 中可以存在的是 一个集合。
<select id="queryBlogForeach" parameterType="map" resultType="com.AL.pojo.Blog">
select * from blog
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from blog where 1=1 and (id=1 or id=2 or id=3)
select * from blog WHERE ( id=? or id=? or id=? )
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
3、测试
@Test
public void testQueryBlogForeach(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
System.out.println(blogs);
session.close();
}
==动态 sql 语句的编写往往就是一个拼接的问题,==去拼接SQL语句,按照SQL的格式,去进行排列组合。
- 为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。
2、缓存
2.1、缓存简介
1、什么是缓存 [ Cache ]?
- 存在内存中的临时数据。
- 将用户经常查询的**数据放在缓存(内存)**中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
2、为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
3、什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
缓存了数据库中数据后, 当你查询数据的时候,直接会去走缓存,如果缓存中有数据,那么就不用走数据库了。 提高了访问效率,增加用户体验。
原来的情形:查询 ->连接数据库。耗费资源,速度慢。
此时:将有可能需要的数据缓存到 内存中, 这样你就可以直接取到。
2.2、Mybatis缓存
在Mybatis中的缓存:
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制缓存。 缓存可以极大地提升查询效率。
-
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
-
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
一级缓存:也叫本地缓存。
- 与数据库 同一次 会话期间 查询到的数据会放在本地缓存中。【所以说是 SqlSession级别的缓存】
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。
要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<cache/>
基本上就是这样。这个简单语句的效果如下:
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- 缓存会使用 最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
- 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
- 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
一级缓存
对于一级缓存的测试:
讲到 一级缓存在 sqlSession中,即测试中的创建sqlSession 和 close() 关闭这一个区间内
测试步骤:
-
开启日志:
-
编写接口类:Mapper:
package com.AL.dao; import com.AL.pojo.User; import org.apache.ibatis.annotations.Param; public interface UserMapper { //根据id查询用户 User queryUserById(@Param("id") int id); }
-
接口实现类,Mapper.xml文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace= 绑定一个对应的Dao/Mapper接口 <mapper namespace="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} --> <mapper namespace="com.AL.dao.UserMapper"> <select id="queryUserById" resultType="com.AL.pojo.User"> select * from user where id = #{id} </select> </mapper>
-
测试:
import com.AL.dao.UserMapper; import com.AL.pojo.User; import com.AL.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class MyTest { @Test public void testQueryUserById(){ SqlSession session = MybatisUtils.getSqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); session.close(); } }
-
结果分析:这表明,这个数据库只开启了一次。说明了mybatis中会默认开启一级缓存。
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections. [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection [org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 1645547422. [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@62150f9e] [com.AL.dao.UserMapper.queryUserById]-==> Preparing: select * from user where id = ? [com.AL.dao.UserMapper.queryUserById]-==> Parameters: 1(Integer) [com.AL.dao.UserMapper.queryUserById]-<== Total: 1 User(id=1, name=鑫仔, pwd=123456) User(id=1, name=鑫仔, pwd=123456) true [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@62150f9e] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@62150f9e] [org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 1645547422 to pool. Process finished with exit code 0
当访问的不是同一个目标时, 即访问 id 1 和id 2 的时候,就会发生缓存失效。
缓存失效
缓存失效的情况:
- 查询不同的东西
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
- 查询不同的Mapper.xml
- 手动清理缓存
查询不同的东西,测试缓存:
一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;
一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!
那么对于查询不同的东西,例如 sqlSession 不一样的话,就造成查询的不一样:
@Test
public void testQueryUserById(){
SqlSession session = MybatisUtils.getSqlSession();
SqlSession session2 = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
UserMapper mapper2 = session2.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
User user2 = mapper2.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
session.close();
session2.close();
}
结果:发现查询 进行了两次,从数据库访问了两次, 没有访问缓存得到数据,因为查询了不同的东西。
结论:每个sqlSession中的缓存相互独立。
[com.AL.dao.UserMapper.queryUserById]-==> Preparing: select * from user where id = ?
[com.AL.dao.UserMapper.queryUserById]-==> Parameters: 1(Integer)
[com.AL.dao.UserMapper.queryUserById]-<== Total: 1
User(id=1, name=鑫仔, pwd=123456)
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 1008315045.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3c19aaa5]
[com.AL.dao.UserMapper.queryUserById]-==> Preparing: select * from user where id = ?
[com.AL.dao.UserMapper.queryUserById]-==> Parameters: 1(Integer)
[com.AL.dao.UserMapper.queryUserById]-<== Total: 1
User(id=1, name=鑫仔, pwd=123456)
false
查询两个不同的目标,但 SqlSession相同:
// 查询的SqlSession 一样,但是查询条件不一样。
@Test
public void testQueryUserById(){
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
UserMapper mapper2 = session.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
User user2 = mapper2.queryUserById(2);
System.out.println(user2);
System.out.println(user==user2);
session.close();
}
结果:
[com.AL.dao.UserMapper.queryUserById]-==> Preparing: select * from user where id = ?
[com.AL.dao.UserMapper.queryUserById]-==> Parameters: 1(Integer)
[com.AL.dao.UserMapper.queryUserById]-<== Total: 1
User(id=1, name=鑫仔, pwd=123456)
[com.AL.dao.UserMapper.queryUserById]-==> Preparing: select * from user where id = ?
[com.AL.dao.UserMapper.queryUserById]-==> Parameters: 2(Integer)
[com.AL.dao.UserMapper.queryUserById]-<== Total: 1
User(id=2, name=天啊, pwd=123456)
false
观察结果:发现发送了两条SQL语句!很正常的理解
结论:当前缓存中,不存在这个数据
对用户信息进行修改后,测试缓存:
工具类的修改:增加有参和无参构造方法。
package com.AL.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
测试:
import com.AL.dao.UserMapper;
import com.AL.pojo.User;
import com.AL.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void testQueryUserById(){
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
mapper.updateUser(new User(2, "aaa", "bbb"));
System.out.println("==================");
User user2 = mapper.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
session.close();
}
}
结果:执行了两次查询。
分析原因:
查询在中间执行了增删改操作后,重新执行了
结论:因为增删改操作可能会对当前数据产生影响
手动清除缓存,缓存失效
手动清理: session.clearCache();//手动清除缓存
// sqlSession相同,手动清除一级缓存
@Test
public void testQueryUserById(){
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
session.clearCache();//手动清除缓存
User user2 = mapper.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
session.close();
}
结果:
[com.AL.dao.UserMapper.queryUserById]-==> Preparing: select * from user where id = ?
[com.AL.dao.UserMapper.queryUserById]-==> Parameters: 1(Integer)
[com.AL.dao.UserMapper.queryUserById]-<== Total: 1
User(id=1, name=鑫仔, pwd=123456)
[com.AL.dao.UserMapper.queryUserById]-==> Preparing: select * from user where id = ?
[com.AL.dao.UserMapper.queryUserById]-==> Parameters: 1(Integer)
[com.AL.dao.UserMapper.queryUserById]-<== Total: 1
User(id=1, name=鑫仔, pwd=123456)
false
小结: 一级缓存默认是开启的,因为它是 SqlSession 级别的,你关闭不了。它只是在一次SqlSession 中有效,即在 拿到连接 到关闭连接的这个区间内。 一级缓存就相当于一个 Map。
二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
-
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
-
工作机制
-
-
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
-
如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
-
新的会话查询信息,就可以从二级缓存中获取内容;
-
不同的mapper查出的数据会放在自己对应的缓存(map)中;
-
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。
要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<cache/>
步骤: 想要进行二级缓存,不是简简单单的一个语句就行了。
-
开启全局缓存:【mybatis-config.xml】
在mybatis-config.xml配置文件中:
<settings> <!--日志工厂实现--> <setting name="logImpl" value="LOG4J"/> <!--显示的开启全局缓存--> <setting name="cacheEnabled" value="true"/> </settings>
-
在要使用二级缓存的Mapper.xml中开启:
也可以自定义它的参数,设置它缓存的格式,如刷新时间等:其实加不加都行。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace= 绑定一个对应的Dao/Mapper接口 <mapper namespace="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} --> <mapper namespace="com.AL.dao.UserMapper"> <!--在当前的Mapper.xml中使用二级缓存--> <cache/> <!-- 官方示例=====>查看官方文档--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> <!-- 这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用, 而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。--> <select id="queryUserById" resultType="com.AL.pojo.User"> select * from user where id = #{id} </select> <update id="updateUser" parameterType="com.AL.pojo.User"> update user set name = #{name} where id = #{id} </update> </mapper>
-
测试:
我们使一个会话关闭,查看是否能缓存到二级缓存中, 必须是同一个Mapper文件。
// 测试二级缓存 @Test public void testQueryUserById(){ SqlSession session = MybatisUtils.getSqlSession(); SqlSession session2 = MybatisUtils.getSqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); UserMapper mapper2 = session2.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); session.close(); User user2 = mapper2.queryUserById(1); System.out.println(user2); System.out.println(user==user2); session2.close(); }
-
结果: 出现错误。
在没有参数的时候,出现了错误:因为没有序列化。
org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException: com.AL.pojo.User
我们需要将实体类 序列化,否则就会报错。要和 二级缓存 xml文件中对应上:
<cache/>
<cache
eviction="FIFO" <!--序列化 -->
flushInterval="60000"
size="512"
readOnly="true"/>
修改实体类,使其序列化:
public class User implements Serializable { // 使其序列化
private int id;
private String name;
private String pwd;
}
小结:
- 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
- 查出的数据都会被默认先放在一级缓存中
- 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中
缓存原理
注意:只有查询才有缓存,根据数据是否需要缓存(修改是否频繁选择是否开启)useCache=“true”
<select id="getUserById" resultType="user" useCache="true">
select * from user where id = #{id}
</select>
自定义缓存-ehcache
第三方缓存实现–EhCache。
Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;
要在程序中使用 ehcache, 先要导包 jar包。 直接导入maven仓库依赖:
mybatis ehcache
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
例子:
1.mapper.xml配置文件中:
<mapper namespace="com.AL.dao.UserMapper">
<!--在当前的Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<select id="queryUserById" resultType="com.AL.pojo.User">
select * from user where id = #{id}
</select>
<update id="updateUser" parameterType="com.AL.pojo.User">
update user set name = #{name} where id = #{id}
</update>
</mapper>
2.在resource资源文件中 添加了 ehcache.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
4.工具类中增加的 MyCache类:
package com.AL.utils;
import org.apache.ibatis.cache.Cache;
public class MyCache implements Cache {
public String getId() {
return null;
}
public void putObject(Object o, Object o1) {
}
public Object getObject(Object o) {
return null;
}
public Object removeObject(Object o) {
return null;
}
public void clear() {
}
public int getSize() {
return 0;
}
}
使用查询语句缓存,那么可以对你需要的数据库的表 进行缓存,加快访问速度。 但是你的表一旦改变了,这个缓存失效了,你还要销毁,浪费资源和时间.
缓存虽然能够提升数据库的查询性能,但是缓存同时也带来了额外的开销,每次查询后都要做⼀ 次缓存操作,失效后还要销毁。 因此,开
启缓存查询要谨慎,尤其对于写密集的应⽤来说更是如此。如果开启,要注意合理控制缓存空间⼤⼩,⼀般来说其⼤⼩设置为⼏⼗MB比较合适。
更多的是采用==Redis数据库来做缓存==!