Mybatis
环境
-
jdk1.8
-
Mysql5.7
-
maven3.6.1
-
IDEA
回顾:
-
JDBC
-
Mysql
-
java基础
-
maven
-
junit
ssm框架:配置文件.最好的方式:看官网
1.简介
1.1什么是mybatis
-
MyBatis 是一款优秀的持久层框架,
-
它支持自定义 SQL、存储过程以及高级映射。
-
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
-
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
-
2013年11月迁移到github
如何获取Mybatis?
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency>
-
中文文档:MyBatis中文网
1.2持久化
数据持久化
-
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
-
内存:断电即失
-
数据库(jdbc),io文件持久化
-
生活:冷藏,罐头.
为什么需要持久化?
-
有一些对象,不能让他丢掉.
-
内存太贵了
1.3持久层
dao层 servlet层 controller层...
-
完成持久化工作的代码块
-
层界限十分明显.
1.4为什么需要mybatis?
-
帮助程序员将数据存入数据库
-
方便
-
传统的JDBC代码太复杂.简化,框架.
-
不用mybatis也可以.更容易上手,技术没有高低之分
-
优点:
-
简单易学:
-
灵活
-
解除sql与程序代码的耦合:
-
提供映射标签,支持对象与数据库的ORM字段关系映射。
-
提供对象关系映射标签,支持对象关系组建维护。
-
提供xml标签,支持编写动态sql。
-
使用的人多
-
2.第一个mybatis程序
搭建数据库
create database 'mybatis'; use mybatis; create table 'user'( 'id' int not null, 'name' varchar default null, 'pwd' varchdefault null primary key('id') )engine=innodb default charset=utf8; insert into 'user'('id','name','pwd')values (1,'asd','123'),(2,'asda','weq');
2.1.新建一个maven项目
2.2.删除src 父工程
2.3.导入依赖
mysql mabtis junit
2.4.创建一个模块mybatis01
-
编写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 核心配置文件--> <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="123"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
-
编写mybatis工具类
public class MybatisUtils{ private static Sqlsessionfactory sqlsessionfactory; static{ try{ //使用Mybatis第一步 获取SQL sessionfactory对象 String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }catch(IOException e){ e.printStackTrace(); } } //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。 public static sqlsession getsqlsession(){ return=sqlsessionfactory.getopensession(); } }
2.5编写代码
-
实体类
@Data publci class User{ private int id; private String name; private String pwd; }
-
dao接口
public interface UserDao{ List<User> getUsers(); }
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"> <!--绑定一个对应的Dao接口--> <mapper namespace="com.qyb.dao.UserDao"> <!--查询语句--> <select id="getUsers" resultType="User"> select * from User where id = #{id} </select> </mapper>
-
接口实现类
public class UserDaoImplimplatement UserDao(){ }
2.6测试
注意点 注册没有
public class UserDaoTest(){ @Test public void test(){ SqlSession sqlSession=MybatisUtils.getsqlsession(); UserDao mapper=sqlsession.getMapper(UserDao.class); return mapper.getUsers(); sqlsession.close(); } }
3.crud
3.1namespace
namespace名字要与dao/mapper接口名一致
3.2select
选择 查询语句:
-
id:就是对应namespace中方法名;
-
resulttype:sql语句执行的返回值.
-
paramtype:参数类型
3.3.insert
3.4.update
3.5.delete
注意点:
-
增删改需要提交事务
4.常见错误
-
编写标签错误<select>就是查询 <insert>就写添加
-
resource绑定mapper,需要使用路径
-
程序配置文件必须符合规范
-
nullpoinception,没有注册到
5.万能的map
加黑色我们的实体类,或者数据库中的字段过多 ,我们应当考虑使用Map
Map传递参数,直接在sql中取出key即可!
对象传递参数,直接在sql中去对象的属性即可.
只有一个基本类型的参属下 可以直接在sql中取到
6.配置解析
1.核心配置文件
-
mybatis-config.xml
2.环境配置(environments)
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
数据源(datasource):dbcp,c3p0 druid
池:用完可以回收
事务管理器(transactionManager ):jdbc
Mybatis默认的事务管理器是JDBC,连接池:POOLED
3.属性(properties)
我们可以通过properties属性来实现引用
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。[db.properties]
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=root password=123
在核心配置文件中引入
<?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> <!--引入外部配置文件--> <properties resource="db.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
4.类型别名(typeAliases)
-
类型别名可为 Java 类型设置一个缩写名字。
-
它仅用于 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> <!--引入外部配置文件--> <properties resource="db.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <!--可以起别名--> <typeAliases Aliase=User type="com.qyb.pojo.User"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers>
还可以指定一个包起别名 扫描实体包 别名就是类名
<typeAlias alias="user" type="com.qyb.pojo.User"/>
实体类比较少的时候使用第一种方式
实体类多了建议使用第二种
第一种可以DIY 第二种不行(但是可以在实体类上加注解@Alias来起别名)
5.设置(settings)
6.映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件:
方式一:
<!-- 使用相对于类路径的资源引用 --> <mappers> <mapper resource="org/mybatis/builder/AuthorMapper.xml"/> </mappers>
方式二:使用class文件绑定:
<mappers> <mapper class="org.mybatis.builder.AuthorMapper"/> </mappers>
注意点:
-
接口和他的Mapper配置文件必须同名
-
接口和他的Mapper配置文件必须在同一个包下
方式三:使用扫描包进行扫描
<!-- 将包内的映射器接口实现全部注册为映射器 --> <mappers> <package name="org.mybatis.builder"/> </mappers>
7.生命周期
生命周期和作用域是很重要的,因为错误的使用会导致很严重的并发问题.
sqlsessionfactorybuilder:
-
一旦创建sqlsessionfactory,就不需要它了
-
局部变量
sqlsessionfactory:
-
说白了就是数据池
-
SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
-
因此 SqlSessionFactory 的最佳作用域是应用作用域
-
最简单的就是使用单例模式或者静态单例模式
sqlsession:
-
连接到数据库的一个请求
-
用完之后要赶紧关闭,否则会资源被占用
7.解决属性名和字段名不一致问题
解决方法:
-
起别名
-
ResultMap
2.ResultMap结果集映射
<!--结果集映射--> <resultMap id='userMap' type="User"> <!--column是数据库中的字段,property是实体类中的属性--> <result column='id' property='id'/> <result column='name' property='name'/> <result column='pwssword' property='pwd'/> </resultMap>
-
resultMap
元素是 MyBatis 中最重要最强大的元素。 -
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
-
ResultMap
的优秀之处——你完全可以不用显式地配置它们
8.日志
1.日志工厂
如果一个数据库的操作出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout , debug
现在 日志工厂
-
SLF4J |
-
LOG4J | 掌握
-
LOG4J2 |
-
JDK_LOGGING |
-
COMMONS_LOGGING |
-
STDOUT_LOGGING | 掌握
-
NO_LOGGING
标准的日志工厂设置
<setting> <setting name="logImpl" value="STDOUT_LOGGING"/> </setting>
2.log4j
什么是log4j?
-
Log4j是Apache的一个开源项目,通过使用Log4j,
-
我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等
-
我们也可以控制每一条日志的输出格式
-
通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
-
这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
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/kuang.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的类中导包log4j
2.日志对象,参数为当前类的class
static logger logger=logger.getlogger(userdao.class); @test public void testlog4j(){ logger.info("info:引入了testlog4j") logger.debug("debug:进入了debug模式") logger.error("error:进入了error模式") }
3.日志级别
logger.info("info:引入了testlog4j") logger.debug("debug:进入了debug模式") logger.error("error:进入了error模式")
9.分页
思考:为什么要分页?
-
减少数据的处理量
使用limit分页语法:
select * from user limit startindex,pagesize; select * from user limit 0,5;
9.1使用mybatis实现分页,核心sql
分页一:
//接口 List<User> getUserBylimit(Map<String,Integer> map); //mapper.xml <select id="getUserBylimit" paramterType="map" resultType="user"> select * from 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<String,Integer>(); map.put("startindex",0); map.put("pagesize",2); List<User> userList=mapper.getUserByLimit(map) System.out.println(userList); sqlSession.close(); }
9.2RowBound
分页二:
@Test public void getUserByLimit2(){ SqlSession sqlSession=MybatisUtils.getSqlSession(); RowBounds rowBounds=new RowBounds(1,2); //通过java代码层面实现分页 List<User> user=sqlSession.selectList("com.qyb.dao.UserMapper",null,rowBounds) System.out.println(user); sqlSession.close(); }
9.3分页插件
MybatisPageHelper
使用方法文档地址:如何使用分页插件
了解就可以了,需要使用了按文档使用 ,底层都一样都是limit;
10.使用注解开发
10.1面向接口编程
根本原因:解耦,可图按照,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,是的卡法变得容易,规范性更好.
10,2面向照注解开发
底层主要使用反射 动态代理
//接口 public interface UserMapper{ @Select("select * from User") List<User> getUser(); } //在mybatis-config.xml中绑定接口 <mappers> <mapper class="com.qyb.dao.UserMapper"/> </mappers>
Mybatis的详细执行流程
首先Resources获取加载全局配置文件
然后实例化SqlSessionFactoryBuilder构造器
解析配置文件流XmlConfigBuild
configration 所有的配置信息
实例化sqlsessionfactory
transaction事务管理器
创建executor执行器
创建sqlsession
实现crud 回滚到事务管理器
是否执行成功 回滚
提交事务
关闭
10.3注解实现crud
我们可以在工具类创建的时候设置自动提交
public static sqlsession getSqlSession(){ return sqlSessionFactory.openSession(true); }
@Select("select * from user where id=#{id}") User getUserByID(@Param("id")int id) @Insert("insert into user values (#{id},#{name},#{password})") int addUser(User user); @Update("update user set name=#{name},password=#{password} where id=#{id}") int updateUser(User user); @delete("delete from user where id=#{uid}") int deleteUser (@Param("uid") int id)
如果方法存在多个参数的时候可以使用注解@Param
注意:一定不要忘了把接口绑定带配置文件中.
关于@Param()注解
-
基本类型的参数或者String类型,需要加上
-
引用类型可以不用加
-
如果只有一个基本类型的话,可以忽略,但是还是加上比较好 建议加上
-
我们在sql中引用的就是你在@Param中设定好的
#{}与${}的区别是什么?
11.lombok
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. Project Lombok是一个java库,它可以自动插入编辑器和构建工具,为您的java增添色彩。 永远不要再编写另一个getter或equals方法,只要有一个注释,您的类就有一个功能齐全的生成器,自动记录变量,等等。
-
java library
-
plugs
-
build tools
使用:
1.在IDEA中安装lombok插件
2.在项目中导包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> <scope>provided</scope> </dependency>
3.注解
@Getter @Setter @ToString @EqualsAndHashCode @AllArgsConstructor @NoargsConstructor @Data
@Data:无参构造 get set tostring ,hashcode equals
12.多对一处理
-
多个学生对应一个老师
-
对于学生而言,关联..多个学生,关联一个老师[一对多]
-
对于老师而言,集合,一个老师有很多学生[多对一]
按照查询嵌套处理
<select id="getStudent" resultMap="StuentTeacher"> </select> <resultMap id="StuentTeacher" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/> <!--复杂的属性,我们需要单独处理 对象:association 集合:collection --> <association property= "teacher" colum="tid" javatype="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id=#{id} </select>
按照结果嵌套处理
<!--按照结果嵌套查询--> <select id="getStuent2" resultMap="StudnetTeacher2"> select s.id sid,s.name sname,t,name tname from student s,teacher t where s.tid=t.id; </select> <resultMap id="StudnetTeacher2" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" column="tname"javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap>
回顾mysql多对一查询:
-
子查询
-
联表查询
13.一对多处理
比如一个老师拥有多个学生
对于来说就是一对多
获取老师下的所有学生以及老师信息
接口:
Teacher getTeacher(@param("tid")int id);
TeacherMapper:
<!--按结果嵌套查询--> <select id="getTeacher" resultMap="TeacherStuent"> 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="TeacherStuent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <!--复杂的属性,我们需要单独处理 对象:association 集合:collection javaType:指定属性的类型 集合中的反省信息,我们使用ofType获取 --> <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="TeacherStudent2"> select * from teacher where id=#{tid}</select> <resultMap id="TeacherStudent2" type="Teacher"> <collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacherID"/> </resultMap> <select id="getStudentByTeacherID" resultType="Student"> select * from student where tid=#{tid} </select>
小结:
1.关联-association[多对一]
2.集合-collection[一对多]
3,javatype&ofType
1.javaType 用来指定实体类中属性的类型
2.ofType 用来指定映射到List或集合中的pojo类型,泛型中的约束类型!
注意点:
-
保证sql的可读性,尽量保证通俗易懂
-
注意一对多和多对一,属性名和字段的问题
-
如果问题不好排查,可以使用日志 建议使用log4j
面试高频
-
mysql引擎
-
innodb底层原理
-
索引
-
索引优化
14.动态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>
chooes
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
where
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
set
<update id="updateAuthorIfNecessary"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id} </update>
trim
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim> <trim prefix="SET" suffixOverrides=","> ... </trim>
所谓的动态sql实质上还是sql语句 ,只是在sql层面执行一个逻辑代码
if
where
set
choose
when
foreach
select * from user where 1=1 and(id=1 or id=2 or id=3)
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
SQL片段
有的时候我们可能会将一些公共的部分抽取出来
<sql id="if-title-authour"> <if test="title !=null"> title=#{title} </if> <if test="authour !=null"> authour=#{authour} </if> </sql> <where> <incluede refid="if-title-authour"></incluede> </where>
使用sql标签抽取公共部分
在使用的地方用incluede调用
注意事项:
-
最好基于单表来定义sql片段
-
不要存在where标签
动态SQL就是在拼接sql语句 我们只需要保证sql的正确性,我们按照sql的格式,去排列组合就可以了
建议:
-
先在mysql中写出完整的sql语句,再去修改我们的动态sql 实现通用即可.
15.缓存
查询: 连接数据库 ,耗资源 一次查询的结果 ,给他放在一个地方下次直接取 不用走数据库了
简介
1、什么是缓存 [ Cache ]?
-
存在内存中的临时数据。
-
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
2、为什么使用缓存?
-
减少和数据库的交互次数,减少系统开销,提高系统效率。
3、什么样的数据能使用缓存?
-
经常查询并且不经常改变的数据。
Mybatis缓存
-
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
-
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
-
默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
-
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
-
为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
-
一级缓存
一级缓存也叫本地缓存:
-
与数据库同一次会话期间查询到的数据会放在本地缓存中。
-
以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试
1、在mybatis中加入日志,方便测试结果
2、编写接口方法
//根据id查询用户User queryUserById(@Param("id") int id);
3、接口对应的Mapper文件
<select id="queryUserById" resultType="user"> select * from user where id = #{id}</select>
4、测试
@Testpublic void testQueryUserById(){ SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); session.close();}
一级缓存失效的四种情况
一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;
一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!
1、sqlSession不同
@Testpublic void testQueryUserById(){ SqlSession session = MybatisUtils.getSession(); SqlSession session2 = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); UserMapper mapper2 = session2.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); User user2 = mapper2.queryUserById(1); System.out.println(user2); System.out.println(user==user2); session.close(); session2.close();}
观察结果:发现发送了两条SQL语句!
结论:每个sqlSession中的缓存相互独立
2、sqlSession相同,查询条件不同
@Testpublic void testQueryUserById(){ SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); UserMapper mapper2 = session.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); User user2 = mapper2.queryUserById(2); System.out.println(user2); System.out.println(user==user2); session.close();}
观察结果:发现发送了两条SQL语句!很正常的理解
结论:当前缓存中,不存在这个数据
3、sqlSession相同,两次查询之间执行了增删改操作!
增加方法
//修改用户int updateUser(Map map);
编写SQL
<update id="updateUser" parameterType="map"> update user set name = #{name} where id = #{id}</update>
测试
@Testpublic void testQueryUserById(){ SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); HashMap map = new HashMap(); map.put("name","kuangshen"); map.put("id",4); mapper.updateUser(map); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); session.close();}
观察结果:查询在中间执行了增删改操作后,重新执行了
结论:因为增删改操作可能会对当前数据产生影响
4、sqlSession相同,手动清除一级缓存
@Testpublic void testQueryUserById(){ SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); session.clearCache();//手动清除缓存 User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); session.close();}
一级缓存就是一个map
二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
-
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
-
工作机制
-
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
-
如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
-
新的会话查询信息,就可以从二级缓存中获取内容;
-
不同的mapper查出的数据会放在自己对应的缓存(map)中;
-
使用步骤
1、开启全局缓存 【mybatis-config.xml】
<setting name="cacheEnabled" value="true"/>
2、去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】
<cache/>官方示例=====>查看官方文档<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
3、代码测试
-
所有的实体类先实现序列化接口
-
测试代码
@Testpublic void testQueryUserById(){ SqlSession session = MybatisUtils.getSession(); SqlSession session2 = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); UserMapper mapper2 = session2.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); session.close(); User user2 = mapper2.queryUserById(1); System.out.println(user2); System.out.println(user==user2); session2.close();}
结论
-
只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
-
查出的数据都会被默认先放在一级缓存中
-
只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中
第三方缓存实现--EhCache: 查看百度百科
Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;
要在应用程序中使用Ehcache,需要引入依赖的jar包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache --><dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.1.0</version></dependency>
在mapper.xml中使用对应的缓存即可
<mapper namespace = “org.acme.FooMapper” > <cache type = “org.mybatis.caches.ehcache.EhcacheCache” /></mapper>
编写ehcache.xml文件,如果在加载时未找到/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:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下: user.home – 用户主目录 user.dir – 用户当前工作目录 java.io.tmpdir – 默认临时文件路径 --> <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"/> <!-- defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。 --> <!-- name:缓存名称。 maxElementsInMemory:缓存最大数目 maxElementsOnDisk:硬盘最大缓存个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 overflowToDisk:是否保存到磁盘,当系统当机时 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。 diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 clearOnFlush:内存数量最大时是否清除。 memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。 FIFO,first in first out,这个是大家最熟的,先进先出。 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。 LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。 --></ehcache>
合理的使用缓存,可以让我们程序的性能大大提升!