学习视频:B站 狂神说Java – https://www.bilibili.com/video/BV1NE411Q7Nx
学习资料:mybatis 参考文档 – https://mybatis.org/mybatis-3/zh/index.html
动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
创建数据库:
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
创建一个基础工程:
编写实体类:
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核心配置文件中 去开启 自动驼峰命名规则。如下所示
<configuration>
<properties resource="db.properties">
properties>
<settings>
<setting name="logImpl" value="LOG4J"/>
<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 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);
}
编写接口实现类:
<mapper namespace="com.AL.dao.BlogMapper">
<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.编写接口: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语句:
<mapper namespace="com.AL.dao.BlogMapper">
<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.测试
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 语句!
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例子: choose (when, otherwise)
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。
针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。还是上面的例子,但是策略变为:
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
从结果中可以发现:只要前面某一个满足了, 就不会执行后面的。
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 标签中的语句要使用 逗号隔开,前面几个标签都没有使用隔开符号。
<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层面,去执行一个逻辑代码.
所谓的动态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>
<include refid="if-title-author">include>
where>
select>
注意:
①、最好基于 单表来定义 sql 片段,提高片段的可重用性
②**、在 sql 片段中不要存在 where**
接口:
List<Blog> queryBlogIFInclude(Map map);
mapper.xml文件修改:
<sql id="if-title-author">
<if test="title != null">
title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
sql>
<select id="queryBlogIFInclude" parameterType="map" resultType="com.AL.pojo.Blog">
select * from blog
<where>
<include refid="if-title-author">include>
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:
动态 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>
<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的格式,去进行排列组合。
1、什么是缓存 [ Cache ]?
2、为什么使用缓存?
3、什么样的数据能使用缓存?
缓存了数据库中数据后, 当你查询数据的时候,直接会去走缓存,如果缓存中有数据,那么就不用走数据库了。 提高了访问效率,增加用户体验。
原来的情形:查询 ->连接数据库。耗费资源,速度慢。
此时:将有可能需要的数据缓存到 内存中, 这样你就可以直接取到。
在Mybatis中的缓存:
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制缓存。 缓存可以极大地提升查询效率。
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
一级缓存:也叫本地缓存。
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。
要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<cache/>
基本上就是这样。这个简单语句的效果如下:
讲到 一级缓存在 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文件:
<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 的时候,就会发生缓存失效。
缓存失效的情况:
一级缓存是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中开启:
也可以自定义它的参数,设置它缓存的格式,如刷新时间等:其实加不加都行。
<mapper namespace="com.AL.dao.UserMapper">
<cache/>
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
<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"
<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文件:
<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>
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数据库来做缓存==!