简介
什么是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:
持久化
数据持久化
- 持久化就是将程序的数据在持久状态向瞬时状态转换的过程
- 内存:断电即失
- 数据库(jdbc)、io文件持久化
- 生活中的持久化:冷藏。
为什么需要持久化?
- 有一些对象不能让他丢掉
- 内存太贵了也不可以一直让他放内存中
持久层
Dao层、Service层、Controller层
- 完成持久化工作的代码块
- 层界限十分明显
为什么使用mybatis
- 方便
- 传统jdbc太复杂了,简化,自动化,框架
- 帮助程序猿将数据存入数据库中
- 不用mybatis也可以,更容易上手
- sql和代码的分离
- 使用的人多
CRUD(配置文件中的关键字)
-
namespace
namespace中的包名要和接口中的包名一致 -
select
选择,查询语句;- id:就是对应的namespace中的方法名
- resultType:sql语句的返回值!
- parameterType:参数类型!
编写接口
public interface UserMapper { //查询 List<User> getUserList(); // 插入 void inseartdata(User u); // 删除 void deletedata(int id); // 更新 void updateData(User u); }
在interface所对应的mapper中编写sql语句
<select id="getUserById" parameterType="int" resultType="com.dj.pojo.user"> select * from mybatis.user where id = #{id} </select>
测试
@Test public void test() { SqlSession sqlsession = mybaitsUtil.getsession(); UserMapper mapper = sqlsession.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } sqlsession.close(); }
-
insert
<insert id="inseartdata" parameterType="com.dj.pojo.user"> insert into test.user (id, name, pwd) values (#{id}, #{name}, #{pwd}); </insert>
-
update
<update id="updateData" parameterType="com.dj.pojo.user"> update user set name = #{name} where id=#{id}; </update>
-
delete
<delete id="deletedata" parameterType="int"> delete from user where id=#{id} </delete>
注意点:
增删改需要提交事务!! -
分析可能发生的错误:
- 标签不要匹配出错
- resource绑定mapper,需要使用路劲
- 程序配置文件必须符合规范
- 空指针异常:没有匹配到资源
-
万能的map
假设我们实体类、数据库中中的表,字段或者参数过多,我们可以考虑使用map//mapper public interface UserMapper { void inseartMap(Map<String, Object> map); }
<insert id="inseartMap" parameterType="map"> insert into user (id,name,pwd) values (#{userId},#{Name},#{PWd}); </insert>
@Test public void inseartDataTwo() { SqlSession session = mybaitsUtil.getsession(); UserMapper mapper = session.getMapper(UserMapper.class); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("userId", "555"); map.put("Name", "zhangwang"); map.put("PWd", "787878"); mapper.inseartMap(map); session.commit(); session.close(); }
map传递参数直接在sql中取出map中的key即可!【parameterType=“map”】
对象传递参数直接在sql中取对象的属性即可!【parameterType=“Object”】
只有一个基本类型参数的情况可以直接在sql中取到!【parameterType这个参数可以省略】
多个参数用map,或者注解 -
模糊查询怎么写
- Java代码在执行的时候,传递通配符
List<user> userList = mapper.selectToBlurry("%la%");
- 在sql拼接中使用通配符!
这种方式容易被sql注入<select id="selectToBlurry" resultType="top.ydjsjy.cc.pojo.user"> select * from test.user where name like "%"#{value}"%"; </select>
- Java代码在执行的时候,传递通配符
配置解析
-
核心配置文件
mybatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
-
环境配置(environments)
mybatis可以集成多个环境配置
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
mybatis默认的事务管理器是JDBC,连接池:POOLED -
属性(properties)
我们可以通过properties属性来实现引用配置文件这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
创建db.properties配置文件
drivers=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT username=root pwd=123123123
在核心配置文件中引入
<properties resource="db.properties"> <property name="username" value="root"/> </properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一字段,优先使用外部配置文件
-
类型别名(typeAliases)
类名别名是为java类型设置的一个短名字
存在的意义仅在于用来减少类完全限定名的冗余<typeAliases> <!--可以给实体类起别名--> <typeAlias type="top.ydjsjy.cc.pojo.User" alias="user"/> </typeAliases>
也可以指定一个包名,MyBatis会在包名下面搜索需要的JavaBean
扫描实体类的包,它默认的别名就是这个类的类名,首字母小写<typeAliases> <package name="top.ydjsjy.cc.pojo"/> </typeAliases>
在实体类比较少的情况下,使用第一种,在实体类比较多的情况下使用第二种
他们的区别在于第一种可以DIY别名,第二种则‘不行’,如果想要修改别名的话,在实体类上增加注解@Alias("uuu") public class User { private int id; private String name; private String password; ... }
-
设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 -
mappers(映射器)
方式一(推荐使用):<mappers> <mapper resource="top/ydjsjy/cc/Dao/UserMapper.xml"/> </mappers>
方式二:
使用class的文件绑定注册<mappers> <mapper class="top.ydjsjy.cc.Dao.UserMapper"/> </mappers>
注意点:
接口和它的mapper配置文件必须同名
接口和她的mapper配置文件必须在同一个包下
方式三:
使用包扫描进行注入<mappers> <package name="top.ydjsjy.cc.Dao"/> </mappers>
和方式二注意点一样
-
生命周期和作用域
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:- 一旦创建就不再需要他了
- 局部变量
SqlSessionFactory:
- 就是数据库连接池
- 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)
- 单例模式和静态单例模式
SqlSession
- 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 连接到连接池的一个请求,需要开启和关闭,用完以后需要关闭,否则资源被占用
上图中mapper就代表一个具体的业务,业务完毕要关闭sqlsession!
resultMap(解决属性名和字段名不一致的问题)
-
发现问题:
数据库字段:
实体类定义的字段,模拟与数据库字段不一致:public class User { private int id; private String name; private String password; }
解决方案:
- 起别名:
<select id="getUserList" resultType="user"> select id,name,pwd as password from test.user </select>
-
引入resultMap
结果集映射<resultMap id="usermap" type="uuu"> <id property="id" column="id"/> <id property="name" column="name"/> <id property="password" column="pwd"/> </resultMap> <select id="getUserList" resultMap="usermap"> select * from test.user </select>
- resultMap是mybatis中最重要最强大的元素
- ResultMap 的优秀之处,虽然你对他已经相当的了解,但是你根本不需要显示的地用到他们
- ResultMap的设计思想是:对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句就只需要描述他们之间的关系就行了。
日志工厂
如果一个数据库中的操作出现了异常,我们需要排错,日志就是最好的助手
- SLF4J
- LOG4J 【重要】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【重要】
- NO_LOGGING
在mybatis中具体使用哪一个日志实现,在核心配置文件中添加esttings来实现
STDOUT_LOGGING: 标准的日志输出
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
LOG4J
创建db.properties:
log4j.rootLogger=DEBUG,console,file
log4j.additivity.org.apache=true
# 控制台(console)
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.ImmediateFlush=true
log4j.appender.console.Target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 日志文件(logFile)
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.ImmediateFlush=true
log4j.appender.file.Append=true
log4j.appender.file.File=./log/dj
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 自定义Appender
#log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
#log4j.appender.im.host = mail.cybercorlin.net
#log4j.appender.im.username = username
#log4j.appender.im.password = password
#log4j.appender.im.recipient = corlin@cybercorlin.net
#log4j.appender.im.layout=org.apache.log4j.PatternLayout
#log4j.appender.im.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用:
- 在要使用的log4j的类中,导入log4j的包
- 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserTest.class);
log4j碰到的坑:
学习的时候 建项目的时候是在父项目下面建立Moudule,然后在父项目的pom文件将所有用到的配置导入,在子模块项目中就不用再导了,由于新建子模块后没有刷新Maven,导致log4j的包没有识别到,提示出了以下错误:
log4j:WARN No appenders could be found for logger (com.netease.qa.testng.TestngRetry).
log4j:WARN Please initialize the log4j system properly.
分页
-
为什么要分页?
减少数据的处理量 -
使用limite分页
语法:1 select * from user limit startIndex,pageSize; select * from user limit 0,3; select * from user limit 3; 如果之给定一个参数的话,就是从第一个到第三个
-
使用mybatis实现分页
- 接口
List<User> getUserOfLimit(Map<String, Integer> map);
- Mapper.xml
<resultMap id="userResultMap" type="User"> <result property="password" column="pwd"/> </resultMap> <select id="getUserOfLimit" parameterType="map" resultMap="userResultMap"> select * from test.user limit #{startIndex},#{pageSize} </select>
- 测试
@Test public void limitSelect() { SqlSession session = MybtaisUtil.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); Map<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex", 2); map.put("pageSize", 3); List<User> userOfLimit = mapper.getUserOfLimit(map); for (User u : userOfLimit) { System.out.println(u); } session.close(); }
- 通过RowBounds来实现分页(了解即可)
不再使用sql来进行分页- 接口
List<User> getUserOfRowBounds();
- mapper.xml
<resultMap id="userResultMap" type="User"> <result property="password" column="pwd"/> </resultMap> <select id="getUserOfRowBounds" resultMap="userResultMap"> select * from test.user; </select>
- 测试:
public void limitofRowBounds() { SqlSession session = MybtaisUtil.getSession(); RowBounds rowBounds = new RowBounds(1, 2); List<User> userList = session.selectList("top.ydjsjy.Dao.UserMapper.getUserOfRowBounds", null, rowBounds); for (User o : userList) { System.out.println(o); } session.close(); }
- 接口
- 接口
使用注解开发
-
实现注解开发
- 注解在接口中实现
@Select("select * from User") List<User> getSelect();
- 在配置文件中绑定接口
<mappers> <package name="top.ydjsjy.dao"/> </mappers>
- 注解在接口中实现
-
本质:
反射机制的实现 -
底层:动态代理
代理对象和真实对象都要实现同一个接口
-
mybatis详细的执行流程:
-
CRUD
我们可以在工具类创建的时候实现自动提交事务!public static SqlSession getSession() { return sqlSessionFactory.openSession(true); }
编写接口,增加注解
@Select("select * from User") List<User> getSelect(); @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})") int insertData(@Param("id") int id, @Param("name") String name, @Param("pwd") String pwd); @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{password})") int insertDataTwo(User u); @Update("update user set name=#{name},pwd=#{pwd} where id = #{id}") int updateData(@Param("id") int id, @Param("name") String name, @Param("pwd") String pwd); @Update("update user set name=#{name},pwd=#{password} where id = #{id}") int updateDataTwo(User u); @Delete("delete from user where id=#{id}") int delteData(int id);
测试成功即可!
-
关于 Param() 注解
- 基本类型的参数或者String类型的参数需要加
- 引用类型不需要加
- 如果只有一个基本类型的话可以忽略,但是建议都加上!
- 我们在SQL中引用的就是我们这里的Param(“uid”)中的属性名
#{} 和 ${} 的区别
#{}:安全
${}:不安全
多对一的处理
- 多个学生对应一个老师
- 对于学生而言,关联。多个学生关联一个老师【多对一】
- 对于老师而言,集合。一个老师有很多学生【一对多】
create table `teacher`
(
`id` int NOT NULL primary key,
`name` varchar(30) default NULL
) ENGINE = innodb
default charset = utf8;
insert into teacher(`id`,`name`) values ('1','杨老师');
# 创建学生表和老师表有一个外键 用来绑定查询
create table `student`
(
`id` int not null primary key,
`name` varchar(30) default null,
`tid` int default null,
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");
按照查询嵌套处理
<select id="getStudent" resultMap="studentTeacher">
select * from student;
</select>
<resultMap id="studentTeacher" type="student">
<association property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
按照结果嵌套处理
<select id="getStudent2" resultMap="studentTeacher2">
select s.id sid, s.name sname, t.id tid, t.name tname from student s, teacher t where s.tid = t.id
</select>
<resultMap id="studentTeacher2" type="student">
<association property="teacher" javaType="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
一对多处理
比如:一个老师拥有多个学生!
对于老师而言,就是一对多的关系!
实体类:
public class Student {
private int sid;
private String sname;
private int stid;
}
public class Teacher {
private int tid;
private String tname;
private List<Student> students;
}
按照结果嵌套处理
<select id="getTeacher" resultMap="teacherStudent">
select *
from teacher t,
student s
where t.tid = s.stid
</select>
<resultMap id="teacherStudent" type="teacher">
<id column="tid" property="tid"/>
<result property="tname" column="tname"/>
<collection property="students" ofType="student">
<result property="sid" column="sid"/>
<result property="sname" column="sname"/>
<result property="stid" column="stid"/>
</collection>
</resultMap>
按照查询嵌套处理
<select id="getTeacherTwo" resultMap="teacherStudentTwo">
select *
from test.teacher
</select>
<resultMap id="teacherStudentTwo" type="teacher">
<id column="tid" property="tid"/>
<result property="tname" column="tname"/>
<collection property="students" javaType="ArrayList" ofType="student" select="getStudent" column="tid"/>
</resultMap>
<select id="getStudent" resultType="student">
select *
from test.student
where stid = #{id};
</select>
可能会发生的错误:
- 实体类中的字段名称和数据库中的字段名称一致,如果在使用按照结果嵌套处理,写sql 的时候,没有为字段起别名,会发生查出来结果错误的情况
- 如果在使用按照查询嵌套处理的时候,resultMap中必须将字段全部去映射,如果只映射集合类型,则会发现查出来结果也是有问题的!
小结:
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaTyep & ofType
javaType是用来指定实体类中属性类型
ofType是用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
注意点:
- 保证sql的可读性,尽量通俗易懂
- 注意一对多和多对一中,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志
动态sql
-
什么是动态sql
动态sql是根据不同的条件生成不同的sql语句
利用动态 SQL,可以彻底摆脱这种痛苦。如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。 在 MyBatis 之前的版本中,需要花时间了解大量的元素。 借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类, 现在要学习的元素种类比原来的一半还要少。 if choose (when, otherwise) trim (where, set) foreach
-
搭建环境
create table blog ( `id` int primary key not null comment '博客id', `titel` varchar(25) not null comment '博客标题', `author` varchar(25) not null comment '博客作者', `create_time` varchar(25) not null comment '博客创建时间', `views` int(30) not null comment '浏览量' )engine=innodb default charset = utf8;
-
创建基础环境
- 编写配置文件
- 编写实体类
public class Blog { private int id; private String titel; private String author; private Date createTime; private int views; }
- 编写实体类对应的Mapper已经实体类对应的Mapper.xml文件
-
IF
<select id="getBlog" resultType="blog"> select * from test.blog where <if test="titel != null"> titel like #{titel} </if> </select> <select id="getBlogTwo" resultType="blog"> select * from test.blog where <if test="titel != null"> titel like #{titel} </if> <if test="author != null"> and author = #{author} </if> </select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
-
choose、when、otherwise
<select id="getBlog" resultType="blog"> select * from test.blog <where> <choose> <when test="titel !=null"> titel like #{titel} </when> <when test="author != null"> and author = #{author} </when> <otherwise> and views = #{views} </otherwise> </choose> </where> </select>
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
如果不写otherwise标签的话,会只执行where以外的sql,如果写了otherwise的标签,如果都不匹配的情况下,就会在where标签外的sql后加上otherwise的sql语句!!!
只要满足第一个条件则不会向下匹配其他条件,如果都不满足的时候,就会走otherwise的标签条件 -
trim(where、set)
<select id="getBlogTwo" resultType="blog"> select * from test.blog <where> <if test="titel != null"> titel like #{titel} </if> <if test="author != null"> and author = #{author} </if> <where> </select>
<update id="updateBlog" parameterType="map"> update test.blog <set> <if test="titel != null"> titel=#{titel} </if> <if test="author != null"> author = #{author} </if> <where> id=#{id} </where> </set> </update>
所谓的动态sql,本质还是sql语句,只是我们可以在sql层面去执行一些逻辑代码。
if、where、set、choose、when -
sql片段
有时候,我们经常会将一些公共的功能抽取出来,方便复用!!- 使用sql标签抽取公共的部分
<sql id="if-titel-author"> <if test="titel != null"> titel = #{titel} </if> <if test="author != null"> author = #{author} </if> </sql>
- 再需要使用的地方使用include标签引用即可
<select id="getBlog" resultType="blog"> select * from test.blog <where> <include refid="if-titel-author"/> </where> </select>
注意事项:
最好基于单表来定于sql片段!
不要存在where的标签! - 使用sql标签抽取公共的部分
-
Foreach
<select id="getBlogForeach" resultType="blog"> select * from test.blog <where> <foreach collection="views" item="view" open="(" separator="or" close=")"> views = #{vidw} </foreach> </where> </select>
最终上图的sql拼接出来如下:
==> Preparing: select * from test.blog WHERE ( views = ? or views = ? ) ==> Parameters: 9999(Integer), 9778(Integer)
一般都是使用map来进行参数传递,map也可以直接传递一个list类型!
collection是代表传过来的集合名称
item代表集合中的一个名称
open代表要拼接的前缀
separator分隔符,代表的是,中间以什么分割
close代表要拼接的后缀
动态sql就是在拼接sql语句,我们只要保证sql的正确性,按照sql的格式进行排列、组合就可以了
建议:
- 先在mysql写出完整的sql,再去修改为我们的动态sql实现通用即可!
缓存
-
简介:
一次查询的结果暂存在一个可以直接取到的地方!放到内存中暂存,放在内存中这些查询的数据,就叫缓存。我们再次查询相同数据的时候直接走缓存,就不用去连接数据库了!!
放在内存中的临时数据
将用户经常查询的数据放到内存中,用户查询数据就不用从磁盘中查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题! -
为什么使用缓存?
为了减少和数据库的交互次数,减少系统开销,提高服务效率 -
什么样的数据能使用缓存?
经常查询并且不经常会改变的数据。 -
Mybatis中的缓存
- MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。
- mybatis系统中默认定义了两个缓存:一级缓存,二级缓存
默认情况下,只有一级缓存开启(sqlsession的缓存,本地缓存)
二级缓存需要我们手动开启和配置,它是基于namespace级别的缓存
为了提高扩展性,mybatis定义了缓存接口cache,我们可以通过实现cache接口来自定义二级缓存。
-
一级缓存
-
测试是否默认开启一级缓存
开启日志
测试一个session中查询两次相同的数据
查看日志
查看日志发现,查询出来的两个对象都是相等的,并且只打开了一次jdbc连接,却输出了两次结果,所以说明一级缓存默认开启! -
测试一级缓存失效
在两次查询之间增加更新操作,日志如下Created connection 77269878. ==> Preparing: select * from test.user; ==> Parameters: <== Columns: id, name, pwd <== Row: 2, ppp, 211212121 <== Row: 3, dj3, 12131313 <== Row: 4, pig, 121112 <== Row: 555, zhangwang, 787878 <== Total: 4 User(id=2, name=ppp, pwd=211212121) User(id=3, name=dj3, pwd=12131313) User(id=4, name=pig, pwd=121112) User(id=555, name=zhangwang, pwd=787878) ==> Preparing: update test.user set name=?, pwd=? where id = ? ==> Parameters: ppp(String), 211212121(String), 2(Integer) <== Updates: 1 ==> Preparing: select * from test.user; ==> Parameters: <== Columns: id, name, pwd <== Row: 2, ppp, 211212121 <== Row: 3, dj3, 12131313 <== Row: 4, pig, 121112 <== Row: 555, zhangwang, 787878 <== Total: 4 ======================================================= User(id=2, name=ppp, pwd=211212121) User(id=3, name=dj3, pwd=12131313) User(id=4, name=pig, pwd=121112) User(id=555, name=zhangwang, pwd=787878) false Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@49b0b76] Returned connection 77269878 to pool. Process finished with exit code 0
查看日志我们发现,两个user对象已经不一样了,返回了false,而且查询的sql 也执行了两次,这就说明缓存失效了。
增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
查询不同的东西,也会使缓存失效!
使用不同的mapper去查询数据,即使去查询相同的数据也会使缓存失效!
手动清除缓存!Opening JDBC Connection Created connection 77269878. ==> Preparing: select * from test.user; ==> Parameters: <== Columns: id, name, pwd <== Row: 2, ppp, 211212121 <== Row: 3, dj3, 12131313 <== Row: 4, pig, 121112 <== Row: 555, zhangwang, 787878 <== Total: 4 User(id=2, name=ppp, pwd=211212121) User(id=3, name=dj3, pwd=12131313) User(id=4, name=pig, pwd=121112) User(id=555, name=zhangwang, pwd=787878) ==> Preparing: select * from test.user; ==> Parameters: <== Columns: id, name, pwd <== Row: 2, ppp, 211212121 <== Row: 3, dj3, 12131313 <== Row: 4, pig, 121112 <== Row: 555, zhangwang, 787878 <== Total: 4 ======================================================= User(id=2, name=ppp, pwd=211212121) User(id=3, name=dj3, pwd=12131313) User(id=4, name=pig, pwd=121112) User(id=555, name=zhangwang, pwd=787878) false Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@49b0b76] Returned connection 77269878 to pool. Process finished with exit code 0
小结:一级缓存默认开启,只在一次SqlSession中有效,也就是拿到连接到关闭连接的区间段。
一级缓存就是一个map
-
-
二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域太低,所以诞生了二级缓存!
-
基于namespace的缓存,一个名称空间,对应一个缓存
-
工作机制:
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中。
如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到了二级缓存中。
新的会话查询信息,就可以从二级缓存中获取数据。
不通的mapper查出的数据会放在自己所对应的map中。 -
使用二级缓存
- 开启全局缓存
<setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存中的mapper开启
<cache/> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
- 测试
执行结果日志如下:@Test public void getUser() { SqlSession session = MybatisUtil.getSession(); SqlSession session2 = MybatisUtil.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); UserMapper mapper2 = session2.getMapper(UserMapper.class); List<User> user = mapper.getUser(); session.close(); // 只有在当SqlSession关闭的时候,二级缓存才会生效 List<User> user2 = mapper2.getUser(); System.out.println("======================================================="); System.out.println(user == user2); session2.close(); }
从日志中可以看到,二级缓存生效了,但是如果不关闭第一个sqlsession的话,会发现二级缓存没有生效Opening JDBC Connection Created connection 1192171522. ==> Preparing: select * from test.user; ==> Parameters: <== Columns: id, name, pwd <== Row: 2, ppp, 211212121 <== Row: 3, dj3, 12131313 <== Row: 4, pig, 121112 <== Row: 555, zhangwang, 787878 <== Total: 4 Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@470f1802] Returned connection 1192171522 to pool. Cache Hit Ratio [top.ydjsjy.dao.UserMapper]: 0.5 ======================================================= true Process finished with exit code 0
- 报错:
如果你的xml文件中,只写了cache的标签,并没有指定参数,可能就会报如下错误:
这个错误是说你的实体类没有序列化,要解决这个错误,我们只需要将实体类进行序列化即可public class User implements Serializable { private int id; private String name; private String pwd; }
- 小结:
- 只要开启了二级缓存,在同一个mapper下就有效
- 所有的数据都会先放到一级缓存中,只有当会话提交或者关闭的时候才会提交到二级缓存中。
- 开启全局缓存
-
-
缓存的原理图
-
自定义缓存-ehcache
ehcache是一种广泛的开源java分布式缓存,主要面向通用缓存- 使用ehcache,导包
<dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.2.1</version> </dependency>
- 在resources文件夹下面创建
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <!-- 磁盘缓存位置 --> <diskStore path="java.io.tmpdir/ehcache"/> <!-- 默认缓存 --> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> </ehcache>
- 在mapper中指定使用这个cache
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
- 使用ehcache,导包