简介
什么是Mybatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis。
- 2013年11月迁移到Github。
如何获取MyBatis
- maven仓库
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
- Github:https://github.com/mybatis/mybatis-3
- 中文文档:mybatis – MyBatis 3 | 简介
持久化
- 持久化就是将程序的数据在持久状态和顺势状态转化的过程
- 内存:断电即失
- 数据库(jdbc),io文件持久化
为什么需要持久化?
- 有一些对象,不能让他丢掉。
- 内存价格昂贵
持久层
Dao层,Service层,Controller层…
- 完成持久化工作的代码块
- 层界限十分明显
为什么需要Mybatis
- 方便使用,帮助程序猿将数据存入到数据库中
- 传统的JDBC代码太过复杂,Mybatis进行简化
第一个Mybatis程序
搭建环境
新建数据库
DROP TABLE IF EXISTS `user` ;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(20) NOT NULL,
`pwd` VARCHAR(50) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES
(1,'钱科如','123456'),
(2,'狂神','123456'),
(3,'刘浩汉','123456'),
(4,'赵烨','123456'),
(5,'张凤梅','123456');
新建项目
1.新建一个普通的Maven项目
2.删除src目录
3.导入maven依赖
- mysql
- mybatis
- junit
创建模块
- 编写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>
<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=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/guan/dao/UserMapper.xml"></mapper>
</mappers>
</configuration>
-
编写mybatis工具类(读取mybatis-config资源,并将方法封装成类,避免每次重复读取)
//sqlSessionFactory----construct---->sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//使用Mybatis第一步,获取sqlSessionFactory对象
try {
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();
}
}
编写代码
-
实体类
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接口
public interface UserDao {
List<User> getUserList();
}
- 接口实现类(由原来的Impl转变为一个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">
<mapper namespace="com.guan.dao.UserDao">
<select id="getUserList" resultType="com.guan.pojo.User">
select *
from `mybatis`.`user`;
</select>
</mapper>
测试
注意点:
Type interface com.guan.dao.UserDao is not known to the MapperRegistry
MapperRegistry:每一个Mapper.xml都需要在Mybatis核心配置文件中注册maven配置文件到处问题
由于maven约定大于配置,可能遇到配置文件无法被导出或生效,结局方案
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
- junit测试
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();
}
}
CRUD
1.namespace
namespace中的包名要和Mapper接口的包名保持一致
2.select
选择,查询语句
- id:对应的namespace中的方法名
- resultType:Sql语句执行的返回值
- parameterType:传入参数类型
1.编写接口
2.编写对应的mapper中的sql语句
3.测试
3.insert
<insert id="insertUser" parameterType="com.guan.pojo.User">
insert into `mybatis`.`user` values (#{id},#{name},#{pwd})
</insert>
4.update
<update id="updateUser" parameterType="com.guan.pojo.User">
update `mybatis`.`user`
set name = #{name},pwd = #{pwd}
where id = #{id};
</update>
5.delete
<delete id="deleteUser" parameterType="int">
delete
from `mybatis`.`user`
where id = #{id};
</delete>
万能Map
假设实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
User insertUser2(Map<String,Object> map);
<insert id="insertUser2" parameterType="map">
insert into `mybatis`.`user` values (#{userID},#{userName},#{password})
</insert>
public void insertUser2() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userID",7);
map.put("userName","李航");
map.put("password","123456");
mapper.insertUser2(map);
sqlSession.commit();
sqlSession.close();
}
模糊查询
在sql拼接中使用通配符!
<select id="vagueGetUser" resultType="com.guan.pojo.User" parameterType="String">
select *
from `mybatis`.`user`
where name like "%"#{value}"%";
</select>
配置解析
核心配置文件
- 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
]
编写一个配置文件
diver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8
name = root
password = 123456
在核心配置中引入
<properties resource="db.properties">
<property name="password" value="123456"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加属性配置
- 同一字段引用顺序:
- 元素体内指定属性
- 外部文件属性
- properties方法体内参数
类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字。
- 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<typeAliases>
<typeAlias type="com.guan.pojo.User" alias="User"></typeAlias>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
<typeAliases>
<package name="com.guan.pojo"/>
</typeAliases>
扫描实体类的包,默认别名为这个类的类名
实体类较少使用第一种,实体类较多使用第二种,也可以在实体类上添加注解:@Alias(“User”)
设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
映射器(mapper)
MapperRegistry:注册绑定Mapper文件
方式一:[推荐使用]
<mappers>
<mapper resource="com/guan/dao/UserMapper.xml"/>
</mappers>
方式二:
<mappers>
<mapper class="com.guan.dao.UserMapper"></mapper>
</mappers>
注意点:
- 接口和Mapper配置文件必须同名!
- 接口和Mapper配置文件必须在同一个包下!
方式三:
<mappers>
<package name="com.guan.dao"/>
</mappers>
注意点:
- 接口和Mapper配置文件必须同名!
- 接口和Mapper配置文件必须在同一个包下!
生命周期和作用域
生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
- 一旦创建了SqlSessionFactory,就不再需要了
- 局部变量
SqlSessionFactory:
- 可以想象为:数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 因此 SqlSessionFactory 的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession:
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
- 用完之后赶紧关闭,否则资源被占用!
这里面的每一个Mapper,都代表了一个具体的业务
映射
解决属性名和字段名不一致的问题
制造问题
数据库中的字段:
新建一个项目,测试实体类字段不一致的情况
测试出现问题User{id=3, name='刘浩汉', password='null'}
解决方法
- 起别名
<select id="getUserById" resultType="User" parameterType="int">
select id,name,pwd as password
from `mybatis`.`user`
where id = #{id};
</select>
resultMap
结果集映射<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="pwd" property="password"></result>
</resultMap>
- resultMap 元素是 MyBatis 中最重要最强大的元素
- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
- ResultMap 的优秀之处——你完全可以不用显式地配置它们
日志
日志工厂
如果一个数据库操作出现了异常,需要排错!日志是最好的助手!
- 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?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
1.导入Maven包<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
#将等级为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/guan.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>
4.Log4j的使用
简单使用
1.在要使用Log4j的类中,导入包Logger.getLogger(UserMapperTest.class);
2.日志对象,参数为当前类的classstatic Logger logger = Logger.getLogger(UserMapperTest.class);
3.日志级别
public void TestLog4j() {
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
}
分页
思考:为什么要分页?
- 减少数据的处理量
使用Limit分页
SELECT & FROM 表 LIMIT startIndex,pageSize
使用Mybatis实现分页,核心SQL
1.接口List<User> getUserByLimit(Map<String,Object> map);
2.Mapper.xml
<select id="getUserByLimit" resultMap="UserMap" resultType="User" parameterType="map">
select *
from `mybatis`.`user` limit #{startIndex},#{pageSize};
</select>
3.测试
public void getUserByLimit() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("startIndex",1);
map.put("pageSize",2);
List<User> user = mapper.getUserByLimit(map);
for (User user1 : user) {
System.out.println(user1);
}
sqlSession.close();
}
注解
使用注解开发
1.注解在接口上实现
@Select("select * from `user`")
List<User> getUsers();
2.需要在核心配置文件中绑定接口
<mappers>
<mapper class="com.guan.dao.UserMapper"></mapper>
</mappers>
3.测试
本质:反射机制代理
底层:动态代理
Mybatis详细的执行流程
CRUD
我们可以在工具类创建的时候实现自动提交事务public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(true); }
1.编写接口,增加注释
@Select("select * from `user`")
List<User> getUsers();
@Insert("insert into `user` values(#{id},#{name},#{pwd})")
void insertUser(@Param("id") int id,@Param("name") String name,@Param("pwd") String pwd);
2.测试
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型,可以忽略,但是建议都加上
- 在SQL中引用的是@Param()中设定的属性名
#{}和${}区别
preparedStatement和Statement的区别,#{}可以防止sql注入
Lombok
使用步骤:
1.在IDEA中安装
2.导入Maven包
3.在实体类上编写注解
说明:
@Data:无参构造,get,set,toString,hashcode,equals
@AllArgsConstructor:有参构造
@NoArgsConstructor:无参构造
多对一
- 多个学生,对应一个老师
- 对于学生这边,关联..多个学生,关联一个老师
- 对于老师而言,集合…一个老师,有很多个学生
创建数据库
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);
测试环境搭建
1.导入lombok
2.新建实体类Teacher,Student
3.建立Mapper接口
4.建立Mapper.xml文件
5.在核心配置文件中绑定注册Mapper接口或文件
6.测试查询是否成功
按照查询嵌套处理
<select id="getStudent" resultType="Student" resultMap="StuCombTea">
select * from `student`
</select>
<resultMap id="StuCombTea" type="Student">
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select *
from `teacher` where id = #{tid};
</select>
按照结果嵌套处理
<select id="getStudent" resultMap="StuCombTea">
select s.id sid,s.name sname,t.name tname
from `student` as s,`teacher` as t
where s.tid = t.id;
</select>
<resultMap id="StuCombTea" type="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
回顾Mysql多对一查询
- 子查询
- 连表查询
一对多
1.环境搭建
老师的实体类
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
按照结果查询
<select id="getTeacher" resultMap="Combine">
select s.id sid,s.name sname,t.name tname,t.id tid
from `teacher` t,`student` s
where t.id = s.tid and t.id = #{id};
</select>
<resultMap id="Combine" 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>
动态SQL
什么是动态SQL:根据不同的条件生成不同的SQL语句
借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
if
choose (when, otherwise)
trim (where, set)
foreach
搭建环境
数据库搭建
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
创建一个基础工程(Mybatis-08)
1.导包
2.编写配置文件
3.编写实体类
4.编写实体类对应Mapper接口和Mapper.xml文件
生成随机id
生成随机id
public class IdUtils {
public static String getId() {
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test() {
System.out.println(IdUtils.getId());
}
}
IF
接口
//查询博客(输入标题查指定,输入作者查指定作者的所有博客,不输入查所有博客)
List<Blog> queryBlogIf(Map map);
xml文件
<select id="queryBlogIf" resultType="Blog" parameterType="map">
select *
from `mybatis`.`blog` where 1 = 1
<if test="title != null">
and title = #{title};
</if>
<if test="author != null">
and author = #{author};
</if>
<if test="views != null">
and views > #{views};
</if>
</select>
测试类
public void queryBlogIF() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("views",5000);
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
choose(when,otherwise)
<select id="queryBlogChoose" resultType="Blog" parameterType="map">
select *
from `mybatis`.blog
<where>
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
trim(where,set)
<update id="updateBlog" parameterType="map">
update `mybatis`.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id};
</update>
SQL片段
有的时候,我们可能会讲一些功能抽取出来,方便复用
1.使用SQL标签抽取公共的部分
<sql id="if-title-test">
<if test="title != null">
and title = #{title};
</if>
<if test="author != null">
and author = #{author};
</if>
<if test="views != null">
and views > #{views};
</if>
</sql>
2.在需要使用的地方使用include标签引用
<select id="queryBlogIf" resultType="Blog" parameterType="map">
select *
from `mybatis`.`blog`
<where>
<include refid="if-title-test"></include>
</where>
</select>
注意事项
- 最好基于单表来定义SQL片段
- 不要存在where标签
Foreach
xml文件
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
##select * from `mybatis`.blog where 1=1 and (id=1 or id=2 or id=3)
select *
from `mybatis`.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
测试类
public void queryBlogForeach() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<String> ids = new ArrayList<>();
ids.add("b5acce451fa1481e90acaad1dcdfa994");
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.commit();
sqlSession.close();
}
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式排列组合即可
建议:
- 先在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可
缓存
简介
查询:连接数据库,消耗资源!
- 一次查询的结果,暂存在一个可以直接取到的地方!—> 内存:缓存
- 再次查询相同数据的时候,直接走缓存,不用走数据库
1.什么是缓存?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,而是从缓存中查询,从而提高了查询效率,解决了高并发系统的性能问题。
2.为什么使用缓存 - 减少和数据库的交互次数,减少系统开销,提高系统效率
3.什么样的数据能使用缓存? - 经常查询而且不经常改变的数据
Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率
- MyBatis系统中默认定了了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也成为本地缓存)
- 二级缓存需要手动开启和配置,居于namespace级别的缓存
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存
一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同义词会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
1.开启日志
2.测试在一个Session中查询两次相同记录
缓存失效情况:
1.查询不同记录
2.增删改操作,可能改变原来数据,必定会刷新缓存
3.手动清理缓存
二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个命名空间,对应一个二级缓存;
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的以及缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存尺寸中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从耳机缓存中获取内容
- 不同的mapper查处的数据会放在自己对应的缓存(map)中
步骤:
1.开启缓存
开启全局缓存
<setting name="cacheEnable" value="true"/>
2.在要使用二级缓存的Mapper中开启
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试
小结
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据到会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
Mybatis缓存原理
自定义缓存Ehcache
Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存
要在程序中使用ehcacche,要先导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
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>