文章目录
MyBatis学习
博主此篇学习笔记是跟随哔哩哔哩UP主:狂神说Java,视频讲解时整理
UP主链接:https://space.bilibili.com/95256449
简介:
MyBatis是一款优秀的持久层框架
它支持定制化SQL、存储过程以及高级映射。
MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
MyBatis可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJO为数据库中的记录。
特点:
- 简单易学、灵活、sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射;
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
使用:
1、搭建环境(如:pom.xml中加入mysql驱动、mybatis、junit一些依赖)
<!-- 导入依赖-->
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
</dependencies>
2、创建一个模块(加入mybatis核心配置文件:mybatis-config.xml(resources文件中创建),mybatis工具类)
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">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 每一个Mapper.XML都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="Mapper/UserMapper.xml"/>
</mappers>
</configuration>
MybatisUtils.java
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.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步:获取sqlSessionFactory对象;
String resource = "mybatis-config.xml";
InputStream inputStream = null;
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//即然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例。
//SqlSession完全包含了面向数据库执行SQL命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3、编写代码(创建pojo包中实体类,mapper接口(相当于dao接口),mapper.xml文件(写sql语句,相当于dao接口的实现类;在resources文件中创建))
User.java
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
UserMapper.java
package com.kx.dao;
import com.kx.pojo.User;
import java.util.List;
public interface UserMapper {
//查询所有
List<User> getUserList();
//根据id查询
User getUser(int id);
//增加一条数据
int insertUser(User user);
//修改数据
int updateUser(User user);
//删除数据
int deleteUser(int id);
}
UserMapper.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">
<mapper namespace="com.kx.dao.UserMapper">
<!-- 查询所有-->
<select id="getUserList" resultType="com.kx.pojo.User">
select * from mybatis.user
</select>
<!-- 根据id查询-->
<select id="getUser" resultType="com.kx.pojo.User">
select * from user where id = #{id}
</select>
<!-- 插入数据-->
<insert id="insertUser" parameterType="com.kx.pojo.User">
insert into user (id,name,pwd) value (#{id},#{name},#{pwd})
</insert>
<!-- 修改数据-->
<update id="updateUser" parameterType="com.kx.pojo.User">
update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
<!-- 删除数据-->
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
</mapper>
4、测试(创建测试类进行创建)
UserDaoTest.java
import com.kx.pojo.User;
import com.kx.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUser(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void insertUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.insertUser(new User(3, "哈哈哈", "46567"));
if (res>0){
System.out.println("插入成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.updateUser(new User(3, "嘿嘿嘿", "75644"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.deleteUser(3);
sqlSession.commit();
sqlSession.close();
}
}
增删改查
namespace
namespace的包名要和mapper接口的包名一致
select、insert、update、Delete
选择,查询语句;
id:就是对应的namespace中的方法名;
resultType:Sql语句执行的返回值
parameterType:参数类型
步骤
1、编写接口
2、编写对应的mapper中的sql语句
3、测试
注意:增删改需要提交事务
配置解析
1、核心配置文件
mybatis-config.xml
MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息
configuration(配置)
properties(属性)
setting(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2、环境配置(environments)
MyBatis可以配置成适应多种环境
注意:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境。
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
3、属性(properties)
可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替代的,既可以在典型的java属性文件中配置,也可通过properties元素的子元素来传递。
编写配置文件
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8
username=root
password=123456
在核心配置文件中映入
<!-- 引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value"root"/>
<property name="pwd" value="123456"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有统一字段,优先使用外部配置文件
4、类型别名(typeAliases)
- 类型别名是为了Java类型设置一个短的名字。
- 存在的意义仅在于用来减少类完全限定名的冗余。
<!-- 可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.kx.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis会在包名下面搜索需要的Java Bean,比如:扫描实体类的包,它的默认别名就为这个类的类名,首字母小写
<typeAliases>
<package name="com.kx.pojo"/>
</typeAliases>
在实体类比较少使,使用第一种方式
若实体类十分多,键入使用第二种
第一种可以DIY别名,第二种则需要在实体上增加注解才可DIY别名
@Alias("user")
public class User{}
5、映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件;
方式一:
<!-- 每一个Mapper.XML都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="Mapper/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.kx.daoUserMapper"/>
</mappers>
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.kx.dao"/>
</mappers>
注意:
方式二和方式三中
- 接口和它的Mapper配置文件必须同名
- 接口和它的Mapper配置文件必须在同一个包下
6、生命周期和作用域
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l6eukVGs-1586162967745)(C:\Users\K.X\AppData\Roaming\Typora\typora-user-images\image-20200331155439999.png)]
生命周期,和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
- 一旦创建了SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory:
- 可以想象为:数据库连接池
- SqlSessionFactory一旦被创建就应该在应用的运行期限一直存在,没有任何理由丢弃它或重新创建另一实例。
- 因此SqlSessionFactory的最佳作用域是应用作用域。
- 最简单的就是使用单例模式或者静态单例模式。
SqlSession
- 连接到连接池的一个请求!
- SqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要关闭,否则资源被占用
解决属性名和字段名不一致的问题
实体类中的属性名和数据库的属性名不一致:
解决方法
方式一:起别名
<select id="getUsers" resultType="user"> select id,name,pwd as password from user where id=#{id} </select>
方式二
resultMap
<!--结果集映射--> <resultMap id="UserMap" type="user"> <!--column数据库中的字段,property实体类中的属性--> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <select id="getUserById" resultMap="UserMap"> select * from user where id = #{id} </select>
- ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。对于没有变化的字段可以不用映射,只对字段不同的映射就好了
<resultMap id="UserMap" type="user"> <!--column数据库中的字段,property实体类中的属性--> <result column="pwd" property="password"/> </resultMap>
日志
日志工厂
如果一个数据库操作,出现了异常,日志就是最好的助手!
logImpl 指定MyBatis所用日志的具体实现,未指定时将自动查找
- SLF4J
- LOG4J
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING
- NO_LOGGING
在Mybatis中具体使用哪一个日志实现,在设置中设定
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中,配置日志
<!--标准工厂日志实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
Log4j
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
1、先导入log4j的包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kx.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
3、配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用
1.在要使用Log4j的类中,导入包import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
3.日志级别
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
分页
完成返回前几条或者中间某几行数据,减少数据的处理量
使用Limit分页
语法:
select * from user limit startIndex,pageSize;
select * from user limit n; #[0,n]
接口
//分页查询
List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml
<!-- 分页查询-->
<select id="getUserByLimit" parameterType="map" resultType="User">
select * from user limit #{startIndex},#{pageSize}
</select>
测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",1);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
使用注解开发
面向接口编程
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
-在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来说就不那么重要了;
-而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
-接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
-接口的本身反映了系统设计人员对系统的抽象理解。
-接口应有两类:
-一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
-一类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
-一个个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
-面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法。
-面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现。
-接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题。更多的体现就是对系统整体的架构
使用注解开发
-
注解在接口上实现
@Select("select * from user") List<User> getUserList();
-
需要在核心配置文件中绑定接口
<mappers> <mapper class="com.kx.dao.UserMapper"/> </mappers>
CRUD
我们可以在工具类创建时实现自动提交事务
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
public interface UserMapper {
@Select("select * from user")
List<User> getUserList();
//方法存在多个参数,所有参数前必须加上 @Param("id")注解
@Select("select * from user where id = #{id}")
User getByID(@Param("id") int id);
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int insertUser(User user);
@Update("update from user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
}
注意:必须要将接口注册绑定到核心配置文件中
关于@Param() 注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 在SQL中引用的是@Param() 中设定的属性名
Lombok
-
在IDEA中安装Lombok插件
-
在项目中导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
-
在实体类中加入注解即可使用
@Data:无参构造,get,set,tostring,hashcode,equals @AllArgsConstructor:有参构造 @NoArgsConstructor:无参构造
联表查询
多对一处理
多个学生对应一名老师
实体类
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
@Data
public class Teacher {
private int id;
private String name;
}
子查询,按照查询嵌套处理
<!-- 思路:
1、查询所有学生
2、根据学生的tid,寻找对应的老师
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,需要单独处理,对象:association,集合:collection-->
<association property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher">
select * from teacher where id = #{id}
</select>
连接查询,按照结果嵌套处理
<!-- 按照结果嵌套处理-->
<select id="getStudent" resultMap="StudentTeacher">
select s.id sid, s.name sname, t.name tname
from student s,teacher t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
一对多处理
一个老师拥有多名学生
实体类:
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多名学生
private List<Student> students;
}
@Data
public class Student {
private int id;
private String name;
private int tid;
}
子查询,按照查询嵌套处理
<select id="getTeacher" resultMap="TeacherStudent">
select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent" type="teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" column="id" javaType="ArrayList" ofType="student" select="getStudentByTeacherID"/>
</resultMap>
<select id="getStudentByTeacherID" resultType="student">
select * from student where tid = #{tid}
</select>
连接查询,按照结果嵌套处理
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname, t.id tid
from student s, teacher t
where s.tid = t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!-- javaType="" 指定属性的类型
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
小结:
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaType & ofType
- JavaType 用来指定实体类中属性的类型
2. ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
- JavaType 用来指定实体类中属性的类型
注意点
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一中,属性名和字段的问题
动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
可以根据不同条件进行SQL拼接。
if
choose ( when, otherwise)
trim (where, set)
foreach
where&if
<select id="queryBlog" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
choose ( when, otherwise)
相当于Java中的switch语句
<select id="chooseBlog" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="author">
and author = #{author}
</when>
<otherwise>
views = #{views}
</otherwise>
</choose>
</where>
</select>
trim(set,where)
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="auther != null">
auther = #{auther}
</if>
</set>
where id = #{id}
</update>
trim标签可自定义格式,实现where与set标签功能
foreach
<!-- select * from blog where 1=1 and (id=1 or id=2 or id=3) -->
<select id="foreachBlog" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用!
-
使用SQL标签抽取公共的部分
<sql id="if-title-author"> <if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
-
在需要使用的地方使用include标签引用即可
<select id="queryBlog" parameterType="map" resultType="blog"> select * from blog <where> <include refid="if-title-author"></include> </where> </select>
注意
- 最好基於单表来定义SQL片段
- 不要存在where标签
缓存
- 什么是缓存
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
- 为什么使用缓存
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
- 什么样的的数据能使用缓存?
- 经常查询并且不经常改变的数据。
Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大地提升查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。可以通过实现Cache接口来自定义二级缓存
一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放到本地缓存中。
- 以后如果需要获取相同的数据,可以直接从缓存中拿,不用再查询数据库;
缓存失效的情况:
-
查询不同的东西
-
增删改操作,可能会改变原来的数据,所以必定会刷新缓存
-
查询不同的Mapper.xml
-
手动清理缓存。
sqlSession.clearCache(); //手动清理缓存
小结:
一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段。
一级缓存相当于是一个map.
二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域低,所以产生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们需要的是,会话关闭,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中;
步骤
-
开启全局缓存
<!--显示的开启全局缓存(默认也是开启)--> <setting name="cacheEnabled" value="true"/>
-
在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存--> <cache/>
也可以自定义参数
<!--在当前Mapper.xml中使用二级缓存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中;
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
缓存顺序
查询顺序
- 先看二级缓存中有没有
- 再看一级缓存中有没有
- 查询数据库