需要具备的基础知识:
框架:是有配置文件的。最好的方式:看官网文档
使用环境:
mysql数据库-8.0.17
junit-4.12
log4j-1.2.17
JDK版本-12
如何获得MyBatis?
Maven仓库
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.3version>
dependency>
github:https://github.com/mybatis/mybatis-3/releases
中文文档:https://mybatis.org/mybatis-3/zh/index.html
数据持久化
为什么需要持久化?
Dao层、Service层、Controller层…
帮助程序员将数据存入到数据库中。
方便
传统的JDBC代码太复杂了。简化、框架、自动化。
不用Mybatis也可以。更容易上手。技术没有高低之分
优点:
最重要的一点:使用的人多!
Spring SpringMVC SpringBoot
思路:搭建环境–>导入Mybatis–>编写代码–>测试!
搭建数据库
CREATE DATABASE `mybatis`;
use `mybatis`;
CREATE TABLE `user`(
`id` INT(20) not null PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`,`name`,`pwd`) VALUES
(1,'狂神','123456'),
(2,'张三','123456'),
(3,'李四','123890')
新建项目
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--父工程-->
<groupId>com.rui</groupId>
<artifactId>MyBatis-Study</artifactId>
<version>1.0-SNAPSHOT</version>
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</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.12</version>
</dependency>
</dependencies>
</project>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
编写mybatis的核心配置文件
<configuration>
<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&characterEncoding=UFT-8"/>
<property name="username" value="root"/>
<property name="password" value="Cc105481"/>
dataSource>
environment>
environments>
configuration>
编写mybatis工具类
package com.rui.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.IOException;
import java.io.InputStream;
//sqlSessionFactory--->SessionFactory
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();
}
}
实体类
package com.rui.pojo;
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 + '\'' +
'}';
}
}
Dao接口
package com.rui.dao;
import com.rui.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
接口实现类由原来的UserImpl转变为一个Mapper配置文件
<mapper namespace="com.rui.dao.UserDao">
<select id="getUserList" resultType="com.rui.pojo.User">
/*定义sql*/
select * from mybatis.user
select>
mapper>
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.rui.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册mappers
junit测试
package com.rui;
import com.rui.dao.UserDao;
import com.rui.pojo.User;
import com.rui.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();
//执行SQL
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
}
可能会遇到的问题:
namespace中的包名要和Dao/mapper接口的包名保持一致
选择查询语句;
编写接口
package com.rui.dao;
import com.rui.pojo.User;
import java.util.List;
public interface UserMapper {
//根据id查询用户
User getUserById(int id);
}
编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.rui.pojo.User" parameterType="int">
/*定义sql*/
select * from mybatis.user where id = #{id};
</select>
测试
@Test
public void getUserById(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
注意点:增删改需要提交事务
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
//万能Map
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{password});
insert>
//万能map
@Test
public void addUser2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userId",4);
map.put("userName","王五");
map.put("password","23333");
mapper.addUser2(map);
//提交事务
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可!【parameterType=“map”】
对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到!
多个参数用Map,或者注解!
模糊查询怎么写?
Java代码执行的时候传递通配符%%
List<User> userList=mapper.getUserLike("%李%");
在sql拼接中使用通配符!
select * from mybatis.user where name like "%"#{value}"%"
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会使用配置多套运行环境!
MyBatis默认的事务管理器就是JDBC,连接池:POOLED
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。【db.properties】
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?
useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=Cc105481
在核心配置文件中引入
类型别名是为 Java 类型设置一个短的名字。
存在的意义仅在于用来减少类完全限定名的冗余。
<typeAliases>
<typeAlias type="com.rui.pojo.User" alias="User"/>
typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类的包,他的默认别名就为这个类的类名,首字母小写!
<typeAliases>
<package name="com.rui.pojo"/>
typeAliases>
在实体类比较少的时候,使用第一种方式。
如果实体类十分多,建议使用第二种方式。
第一种可以DIY别名,第二种则不行,如果非要改,需要在实体类(pojo)上增加@Alias注解
@Alias("author")
public class Author {
...
}
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
生命周期,和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder
一旦创建了SqlSessionFactory,就不再需要它了
可以想象为:数据库连接池
SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
因此SqlSessionFactory的最佳作用域是应用作用域。
最简单的就是使用 单例模式 或者静态单例模式
SqlSession
连接到连接池的一个请求!
SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
用完之后需要赶紧关闭,否则会占用资源
这里的每一个Mapper,就代表一个具体的业务!
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况。
public class User {
private int id;
private String name;
private String pwd;
}
//select * from mybatis.user where id = #{id}
//类型处理器
//select id,name,pwd from mybatis.user where id = #{id}
解决方法:
select id,name,pwd as password from mybatis.user where id = #{id}
结果集映射
id name pwd
id name password
<resultMap id="UserMap" type="User">
<result column=" id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="getUserById" resultMap="UserMap" parameterType="int">
/*定义sql*/
select * from mybatis.user where id = #{id};
select>
resultMap
元素是 MyBatis 中最重要最强大的元素ResultMap
最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!
曾经:sout、debug
现在:日志工厂
在Mybatis中具体使用那个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中,配置我们的日志!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
什么事log4j
1.先导入log4j的包
<dependencies>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
dependencies>
2.log4j.properties
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
3.配置log4j为日志实现
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
4.log4j的使用!直接测试运行刚才的查询
DEBUG [main] (LogFactory.java:105) - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] (LogFactory.java:105) - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] (PooledDataSource.java:353) - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] (PooledDataSource.java:353) - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] (PooledDataSource.java:353) - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] (PooledDataSource.java:353) - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] (JdbcTransaction.java:136) - Opening JDBC Connection
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
DEBUG [main] (PooledDataSource.java:424) - Created connection 2049051802.
DEBUG [main] (JdbcTransaction.java:100) - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7a220c9a]
DEBUG [main] (BaseJdbcLogger.java:143) - ==> Preparing: /*定义sql*/ select * from mybatis.user where id = ?;
DEBUG [main] (BaseJdbcLogger.java:143) - ==> Parameters: 1(Integer)
DEBUG [main] (BaseJdbcLogger.java:143) - <== Total: 1
User{id=1, name='狂神', password='123456'}
DEBUG [main] (JdbcTransaction.java:122) - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7a220c9a]
DEBUG [main] (JdbcTransaction.java:90) - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7a220c9a]
DEBUG [main] (PooledDataSource.java:381) - Returned connection 2049051802 to pool.
Disconnected from the target VM, address: '127.0.0.1:58296', transport: 'socket'
Process finished with exit code 0
简单使用
在要使用Log4j 的类中,导入org.apache.log4j.Logger;
日志对象,加载参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
日志级别
logger.info("info:进入了testLog4j方法");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
思考:为什么要分页?
select * from user limit startIndex,pageSize
使用Mybatis实现分页,核心SQL
接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
select>
测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
不再使用SQL实现分页
接口
List<User> getUserByRowBounds();
mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
select>
测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(1, 2);
//通过java代码层面实现分页
List<User> userList = sqlSession.selectList("com.rui.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
了解即可,万一以后公司的架构师,说要使用,只需要知道它是什么东西!
面向接口编程的根本原因:解耦,可拓展,提高复用,分层开发中、上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性好
注解在接口上实现
@Select(value = "select * from user")
List getUsers();
需要在核心配置文件中绑定接口!
测试
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//底层主要应用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
}
本质:反射机制实现
底层:动态代理!
我们可以在工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
public interface UserMapper {
@Select(value = "select * from user")
List getUsers();
//方法存在多个参数,所有的参数前面必须加上@Param注解
@Select("select * from user where id = #{id} or name = #{name}")
User getUserByID(@Param("id")int id,@Param("name")String name);
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set name = #{name},pwd = #{password} where id = #{id}")
int updateUser(User user);
@Delete("delete from user where id = #{uid}")
int deleteUser(@Param("uid") int id);
}
测试类
【注意:我们必须要将接口注册绑定到我们的核心配置文件中!】
关于@Param()注解
#{} ${}区别
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
使用步骤:
在IDEA中安装Lombok插件
在项目中导入lombok的jar包
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.10version>
dependency>
在实体类上加注解即可
@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
experimental @var
@UtilityClass
Lombok config system
说明:
@Data:无参构造,get、set、toSring、hashcode、equals
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
多对一:
SQL:
CREATE TABLE `teacher`(
`id` int(10) Not null,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher(`id`,`name`) VALUES (1,'秦老师');
CREATE TABLE `student`(
`id` int(10) Not null,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid`(`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO student(`id`,`name`,`tid`) VALUES (1,'小明',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES (2,'小红',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES (3,'小张',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES (4,'小李',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES (5,'小王',1);
回顾Mysql多对一查询方式:
比如:一个老师拥有多个学生!
对于老师而言,就是一对多的关系!
实体类
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List students;
}
@Data
public class Student {
private int id;
private String name;
private int tid;
}
注意点:
慢SQL 1S 1000S
面试高频
什么事动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
利用动态SQL这一特性可以彻底摆脱这种痛苦
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
CREATE TABLE `bolg`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) not null comment '博客标题',
`author` VARCHAR(30) not null comment '博客作者',
`creat_time` datetime not null comment '创建时间',
`views` int(30) not null comment '浏览量'
)ENGINE=InnoDB DEFAULT CHARSET=utf8
创建一个基础工程
导包
编写配置文件
编写实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date creatTime;
private int views;
}
编写实体类对应的Mapper接口和Mapper.xml
@Test
public void queryBlogIF(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("author","尹锐");
List blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
select * from mybatis.bolg
<where>
<if test="title != null">
title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
where>
update mybatis.bolg
title = #{title},
author = #{author},
where id = #{id}
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一些逻辑代码
if
Where,set,choose,when
有的时候,我们可能会将一些公共的部分抽取出来,方便复用!
使用SQL标签抽取公共的部分
title = #{title}
and author = #{author}
在需要使用的地方使用Include标签引用即可
注意事项:
select * from user where 1=1 and
<foreach item="id" index="index" collection="ids"
open="(" separator="or" close=")">
#{id}
</foreach>
(id=1 or id=2 or id=3)
<select id="queryBlogForeach" parameterType="map" resultType="com.rui.pojo.Blog">
select * from mybatis.bolg
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id = #{id}
foreach>
where>
select>
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
查询 : 连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方!--->内存 : 缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
什么事缓存[Cache]?
存在内存中的临时数据。
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,
从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
为什么使用缓存?
什么样的数据能使用缓存?
测试步骤:
缓存失效的情况:
查询不同的东西
增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
查询不同的Mapper.xml
手动清理缓存!
sqlsession.clearCache(); //手动清理缓存
小节:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!
一级缓存就是一个Map。
步骤:
开启全局缓存
<setting name="cacheEnabled" value="true"/>
在要使用二级缓存的Mapper中开启
<cache/>
也可以自定义参数
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
测试
问题:我们需要将实体类序列化!否则就会报错
java.io.NotSerializableException: com.rui.pojo.User
小结:
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
要在程序中使用ehcache,先要导包!
<dependency>
<groupId>org.mybatis.cachesgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.1.0version>
dependency>
然后在mapper中指定使用ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
导入配置文件 ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.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>