mybatis学习笔记
mybatis中文文档地址
搭建环境
- 创建普通的maven项目(maven设置不要是idea环境的,在设置maven里面的路径是否为自己安装的路径,如果不是改成自己的安装的maven环境路径:Bundled (Maven 3)就是idea的环境需要切换)
- 删除src目录,导入依赖
<!-- 导入依赖 -->
<dependencies>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
- 在resources下编写mybatis核心配置文件
<?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核心配置文件 -->
<configuration>
<!--环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--在xml中&符号需要转义:&useSSL:安全连接;useUnicode:使用编码;characterEncoding:utf-8-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="r***"/>
<property name="password" value="****"/>
</dataSource>
</environment>
</environments>
</configuration>
idea连接mysql
- 右侧Database添加选择mysql
- 第一次需要下载mysql驱动
- 点击Test Connection如果提示Server returns invalid timezone. Go to ‘Advanced’ tab and set ‘serverTimezone’ prope,在Advanced里这是时区就可以了:serverTimezone的value为:Hongkong
- 在Schemas里选择需要链接的库
创建mybatis工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 使用mybatis第一步就是获得sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
编写代码
- 实体类
- Dao接口
public interface UserDao {
List<User> getUserList();
}
- 接口实现类由原来的UserDaoImpl转变成一个Mapper配置文件
<?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="com.zeng.dao.UserDao">
<select id="getUserList" resultType="com.****.pojo.User">
select * from mybatis.user
</select>
</mapper>
测试
使用junit
CRUD
- namespace
namespace中的包名要和Dao/Mapper接口的包名一致 - select
选择、查询语句
id:就是对应的namespace中的方法名
resultType:sql语句执行的返回值!
parameterType:参数类型
编写接口
// 根据id查询用户
User getUserById(int id);
编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.****.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
测试
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
- 注意点
增删改需要提交事务:sqlSession.commit();
map使用
数据库中的表,字段过多,可以考虑使用map!
// map
int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来,传递map的key-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{userpwd})
</insert>
@Test
public void test6(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userid",1233);
map.put("username","1990");
map.put("userpwd","1990");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可!【parameterType=“map”]
对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”]
只有一个基本类型参数的情况下,可以直接在sql中取到!
多个参数用Map,或者 注解 !
模糊查询?
- Java执行代码的时候,传递通配符 %%
select * from user where name like "%" #{value} "%"
- 在sql拼接中使用通配符
List<User> users = mapper.getUserLike("%xiao%");
配置解析
核心配置文件
mybatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
环境配置(environments)
MyBatis可以配置成适应多种环境
尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境
学会使用配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties
元素的子元素来传递。【db.properties】
编写一个配置文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=****1234
在核心配置文件中引入
<!-- 引入外部配置文件 -->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="1234"/>
</properties>
· 可以直接引入外部文件
· 可以在其中增加一些属性配置
· 如果两个文件有同一个字段,优先使用外部配置文件的!
类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置
- 降低冗余的全限定类名书写
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.****.pojo.User" alias="User"/>
</typeAliases>
- 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如
- 会使用 Bean 的首字母小写的非限定类名来作为它的别名
<typeAliases>
<package name="com.zeng.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式
如果实体类十分多,建议使用第二种。
第一种可以自定义别名,第二种如果需要自定义别名可以使用注解,例:
@Alias("user")
public class User {}
设置
MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
其它配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
映射器(mappers)
MapperRegistry:注册绑定我们的mapper文件
方式一:
<!-- 每一个mapper.xml都需要在Mybatis核心配置文件中注册!-->
<mappers>
<mapper resource="com/****/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper resource="com.****.dao.UserMapper"/>
</mappers>
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.zeng.dao"/>
</mappers>
方式二和三注意点:
- 接口和他的mapper配置文件必须同名
- 接口和他的mapper配置文件必须在同一个包下
生命周期和作用域
生命周期和作用域,错误的使用会导致非常严重的并发问题。
SqlSession Factory Builder:
- 旦创建了 SqlSession Factory,就不再需要它了
- 局部变量
Sqlsession Factory - 说白了就是可以想象为:数据库连接池
- SqlSession Factory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建
另一个实例。 - 因此 SqlSession Factory的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式。
Sqlsession - 连接到连接池的一个请求
- Sqlsession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用
用完之后需要赶紧关闭,否则资源被占用
解决属性名和字段名不一致的问题
数据库表字段和实体类字段名称不一致问题
解放方法:
- 起别名
<select id="getUserById" resultType="user" parameterType="int">
select id,name,pwd as password from user where id = #{id}
</select>
<!--结果集映射 -->
<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="getUserBy" resultMap="UserMap">
select * from user where id = #{id}
</select>
- resultMap元素是 MyBatis中最重要最强大的元素
- ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句
只需要描述它们的关系就行了。 - Resu tmAp最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。
- 如果世界总是这么简单就好了。
日志工厂
可以记录日志的
- SLF4J
- LOG4]
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING
- NO_LOGGING
在Mybatis中具体使用那个一日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中,配置我们的日志!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
Log4j
什么是Log4j?
- og4是 Apache的一个开源项目,通过使用Log4,我们可以控制日志信息输送的目的地是控制台、文件
GU组件 - 我们也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
- 导入log4j的包
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
- log4j.properties
#将等级为DEBG的日志信息输出到 console和ie这两个目的地, console和ie的定义在下面的代
log4j.rootLogger=DEBUG,console,file
控制台输出的相关设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
log4].appender.console.layout=org.apache.log4j.PatternLayout
log4.appender.console.layout.ConversionPattern=[%c]-%6m%n
#文件输出的相关设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/zeng.log
log4j.appender.file.MaxFilesize=10mb
log4].appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.Conversion.Pattern=[‰p][‰dyy-MM-d][‰c]‰m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
1og41.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.Resultset=DEBUG
log4j.logger.java.sql.Preparedstatement=DEBUG
--------------------------------------------------------------------------------------------------------------
上面不行可以用一下的配置
# priority :debug<info<warn<error
#you cannot specify every priority with different file for log4j
log4j.rootLogger=debug,stdout,info,debug,warn,error
#console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= [%d{yyyy-MM-dd HH:mm:ss a}]:%p %l%m%n
#info log
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.info.File=./log/info.log
log4j.appender.info.Append=true
log4j.appender.info.Threshold=INFO
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#debug log
log4j.logger.debug=debug
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.debug.File=./log/debug.log
log4j.appender.debug.Append=true
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#warn log
log4j.logger.warn=warn
log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.warn.File=./log/warn.log
log4j.appender.warn.Append=true
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.layout=org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#error
log4j.logger.error=error
log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.error.File = ./log/error.log
log4j.appender.error.Append = true
log4j.appender.error.Threshold = ERROR
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
- 配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用
4. 在要使用Log4的类中,导入包 import org. apache log4.oger;
5. 日志对象,参数为当前类的ass
static Logger logger = Logger.getLogger(UserDaoTest.class);
- 日志级别
logger.info("info:进入了testlog4j");
logger.debug("debug:进入testlog4j");
logger.error("error:进入了testlog4j");
分页
使用limit分页
语法: SELECT * from user limit startIndex, pagesize;
SELECT from user limit 0,3;
- 接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
- Mapper.xml
<select id="getUserByLimit" parameterType="map" resultType="User" resultMap="UserMap">
select * from user limit #{startIndex},#{pageSize}
</select>
- 测试
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex", 1);
map.put("pageSize", 2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
分页插件:MyBatis分页插件PageHelper
使用注解开发
- 注解接口开发
@Select("select * from user")
List<User> getUsers();
- 需要在核心配置文件中绑定接口!
<mappers>
<mapper class="com.****.dao.UserMapper"/>
</mappers>
- 测试
- 本质:反射机制实现。底层:动态代理!
mybatis详细的执行流程
注解CRUD
- 可以在工具类创建的时候实现自动提交事务,参数设置为:true
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
- 编写接口增加注解
// 方法存在多个参数,所有的参数前面必须加上@Param("id")注解
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
@Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
int insertUser(@Param("id") int id,@Param("name") String name ,@Param("pwd") String pwd);
@Update("update user set name=#{name} where id = #{id}")
int updateUser(@Param("name") String name,@Param("id") int id);
@Delete("delete from user where id=#{id}")
int delUser(@Param("id")int id);
- 测试
User user = mapper.getUserById(1);
mapper.insertUser(5,"zeng","321");
mapper.updateUser("tjhd",5);
mapper.delUser(5);
【注意:必须将接口的注册绑定到核心配置文件中!】
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议加上!
- 在sql中引用的就是我们在@Param中设置的属性名!
lombok
使用步骤
- idea安装lombok插件
- pom文件导入lombok依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
</dependencies>
- 在实体类上加注解
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
多对一处理
方式一:按照查询嵌套处理
<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 property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<!-- 复杂的属性,需要单独处理 对象:association 集合:collection -->
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
方式二:按照结果嵌套处理
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id tid,s.name sname,t.name tname
from student s,teacher t
where t.id=s.tid
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
一对多处理
按照结果嵌套处理
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid from teacher t,student s
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"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent1">
select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent1" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{id}
</select>
- 关联 - assocition 【多对一】
- 集合 - collection 【一对多】
- javaType:用来指定实体类中属性的类型
- ofType:用来指定映射到list或者集合中的pojo类型,泛型中的约束类型!
注意点:
- 保证SQL的可读性,尽量保证俗易懂
- 注意一对多和多对一中,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用Log4j
动态sql
根据不同的条件生成不同的sql,所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
IF
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
trim、where、set
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
----------------------------------------------------------------------------------------------------------------------------------------
<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>
choose、when、otherwise
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and title = "Java"
</otherwise>
</choose>
</where>
</select>
sql片段
方便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 blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
- 最好基于单表来定义sql片段!
- 不要存在where标签
foreach
通过多个id查询
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach item="id" collection="ids"
open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
@Test
public void test5(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap hashMap = new HashMap();
ArrayList<String> ids = new ArrayList<>();
ids.add("fe4f0f55935a4d12b9dc92b0c3de1820");
ids.add("56e02d9980324389bcc8ea3bb152c380");
ids.add("fee2e47452504653b240171bb63b6004");
hashMap.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(hashMap);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
动态sql就是在拼接sql’语句,我们只要保证sql的正确性,按照sql的格式,去排列组合就可以了
建议:
- 现在mysql中写出完整得sql,再对应的去修改成为我们的动态sql实现即可!
缓存
简介
- 什么是缓存?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文
询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据
Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
。默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
。二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
。为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
一级缓存
一级缓存也叫本地缓存:SqlSession
与数据库同一次会话期间査询到的数据会放在本地缓存中。
以后如果需要获取相同的数据,直接从缓存中拿,没必须再去査询数据库
- 测试步骤:
- 开启日志
- 测试在一个session中查询两次相同的记录
- 查看日志输出
- 缓存失效的情况:
- 查询不同的东西
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
- 查询不同的mapper.xml
- 手动清理缓存
- 小结:一级缓存默认是开启的,只在一次sqlsession中有效,也就是拿到连接到关闭连接这个区间段!
二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存;
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
- 工作机制
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
新的会话查询信息,就可以从二级缓存中获取内容;
不同的mapper查出的数据会放在自己对应的缓存(map)中; - 步骤:
- 开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存的mapper中开启
<!--在当前的mapper.xml中使用二级缓存-->
<cache/>
也可以自定义参数
<cache eviction="FIFO"
flushInterval="600000"
size="512"
readOnly="true"/>
问题:需要将实体类序列化!否则就会报错!
java.io.NotSerializableException
- 小结:只要开启了二级缓存,在同一个mapper下就有效;所有的数据都会先放在一级缓存中;只有当会话提交,或者关闭的时候,才会提交到二级缓存中!