环境:
回顾:
JDBC
Mysql
java基础
Maven
Junit
ssm框架:
MyBatis 是一款优秀的持久层框架,
它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。
2013年11月迁移到Github。
如何获得Mybatis?
maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
数据持久化
为什么需要持久化
有一些对象,不能让他丢掉
Dao层,Service层,Controller层
帮助程序员将数据存入数据库中
方便
传统的JDBC太复杂,简化。框架。自动化
优点:
简单易学:没有任何第三方依赖,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
提供映射标签,支持对象与数据库的orm字段关系映射
提供对象关系映射标签,支持对象关系组建维护
提供xml标签,支持编写动态sql。
思路:搭建环境-->导入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,‘李四‘,789456),
(3,‘王五‘,822565)
新建项目
1.新建一个普通的maven项目
2.删除项目下的src文件
3.导入maven依赖
<!--导入依赖架包-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
编写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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode&characterEncoding=UTF-8&serverTimeZone=Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="dh099023"/>
</dataSource>
</environment>
</environments>
</configuration>
编写Mybatis工具类
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* 工具类 创建sqlSessionFactory工厂,工厂用来生产可执行sql命令的对象SqlSession
* sqlSessionFactory--->Sqlsession
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
//静态代码块。初始就会进行加载操作
static{
try{
//获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e)
{
e.printStackTrace();
}
}
//已经存在sqlSessionFactory,就可以从工厂中获取sqlSesision的实例
//sqlSession包含了面向数据库执行sql命令所需的所有方法
public static SqlSession getSqlSession()
{
return sqlSessionFactory.openSession();
}
}
实体类
public class User {
private int id;
private String name;
private String 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 {
public 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.zwq.dao.UserDao">
<!--这里的id对应原来的方法名字-->
<!--这里利用标签相当于实现UserDao接口的实现类-->
<!--resultType最终返回结果为执行数据库操作的结果集,
通俗来说需要有一个承载结果的容器来封装结果,Type是结果类型,需要将它返回到User
中,这里要使用全限定类名,这里不理解可以去看一下反射机制
-->
<select id="getUserList" resultType="com.zwq.pojo.User">
select * from mybatis.user
</select>
</mapper>
MapperRegistry是什么?
核心配置文件中注册mappers
junit测试
public class UserDaoTest {
@Test
public void test()
{
//获取SqlSession对象
SqlSession sqlSession=MybatisUtils.getSqlSession();
//执行sql
//利用反射机制通过获取UserDao的class文件来创建一个对象
sqlSession.getMapper(UserDao.class);
UserDao userDao=sqlSession.getMapper(UserDao.class);
List<User> userList=userDao.getUserList();
for (User user:userList
) {
System.out.println(user);
}
sqlSession.close();
}
}
可能遇到的问题
配置文件没有注册
绑定接口错误
方法名 错误
返回类型错误
Maven导出资源问题
namespace中的包名要和 Dao/Mapper 接口的包名一致!
选择,查询语句;
id:就是对应的namespace中的方法名
resultType:Sql语句执行的返回值!
paramerType:参数类型
编写接口
//根据id查询用户
User getUserById(int id);
编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.zwq.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
测试
@Test
public void getUserById()
{
SqlSession sqlSession=MybatisUtils.getSqlSession();
//sqlSession.getMapper(UserMapper.class);相当于 UserMapper usermapper=new UserMapperImpl();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
User user=mapper.getUserById(41);
System.out.println(user);
sqlSession.close();
}
<insert id="addUser" parameterType="com.zwq.pojo.User">
insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.zwq.pojo.User">
update mybatis.user set name =#{name},pwd=#{pwd} where id = #{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
注意点:
Map的妙用
假设实体类对应的字段参数过多可以使用map
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
MyBatis可以配置成适应多种环境,但每个SqlSessionFactory实例只能选择一种环境。
MyBatis默认的失误管理器就是JDBC,连接池:POOLED
可以通过properties读取配置文件
在resources下创建一个db.properties(账号密码需修改)
driver=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=roo
password=dh099023
在核心配置文件中引入
<?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="cn/ruanqinlong/mapper/UserMapper.xml"/>
</mappers>
</configuration>
外部文件和内部配置重名时,优先使用外部配置文件
通过在核心配置文件中为类取别名来方便操作。
<typeAliases>
<typeAlias type="cn.ruanqinlong.pojo.User" alias="User"/> </typeAliases>
<package name="cn.ruanqinlong.pojo"/>
极其重要的部分
MapperRegistry:绑定mapper文件
方式一:(每个mapper文件使用路径的方式绑定)
<mappers>
<mapper resource="cn/ruanqinlong/mapper/UserMapper.xml"/> </mappers>
方式二:(使用class进行绑定)
<mappers>
<mapper class="cn.ruanqinlong.mapper.UserMapper"></mapper>
</mappers>
该方法必须mapper类与文件同名并且在同一文件夹下
方法三:(包扫描)
<mappers>
<package name="cn.ruanqinlong.mapper"/>
</mappers>
生命周期和作用域是至关重要的,错误的使用会导致非常严重的并发问题
SqlSessionFactoryBulider:
SqlSessionFactory:
SqlSession:
数据库中字段名与实体类属性名不一致时产生问题
数据库中字段名为id name pwd
实体类属性名为 id name password
数据库查询结果:
解决方案:
方案一:起别名
<select id="getUserById" resultType="com.zwq.pojo.User" parameterType="int" >
select id,name,pwd as password from mybatis.user where id=#{id}
</select>
方案二:结果集映射(Usermapper.xml)
<!--resultMap结果集映射-->
<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="getUserById" resultMap="UserMap" parameterType="int">
<!--select * from mybatis.user where id = #{id}-->
<!--select id,name,pwd as password from user where id = #{id}-->
select * from mybatis.user where id = #{id}
</select>
resultMap
元素是MyBatis中最重要和最强大的元素
ResultMap
的设计使得简单的语句根本不需要显式的结果映射
如果一个数据库操作异常,需要排除,所以就需要日志。
在MyBatis中具体使用哪一个日志,在配置文件中配置
SLF4J
LOG4J 掌握
LOG4J2
JDK_LOGGING
COMMONS_LOGGING
NO_LOGGING
STDOUT_LOGGING Java自带的标准日志输出文件
<settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>
什么是log4j
使用第一步导入log4j的包
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.1</version>
</dependency>
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/zwq.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
配置log4j为日志实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用
使用log4j的类中,导入import org.apache.log4j.Logger;
日志对象,参数为当前类的字节码文件
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;
select = from user limit 3;#[0,n]
使用Mybayis实现分页,核心为SQL
接口
List<User> getUserByLimit(Map<String,Integer> map);
Mapperx.xml
<!--分页实现查询-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from user limit #{startIndex},#{pageSize}
</select>
测试
public void getUserByLimit()
{
SqlSession sqlSession=MybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
HashMap<String,Integer> map=new HashMap<String,Integer>();
map.put("startIndex",1);
map.put("pageSize",2);
List<User> users=mapper.getUserByLimit(map);
for (User user:users
) {
System.out.println(user);
}
sqlSession.close();
}
不在使用SQL实现分页
接口
List<User> getUserByRowBounds();
mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
select * from user
</select>
测试
public void getUserByRowBounds()
{
SqlSession sqlSession=MybatisUtils.getSqlSession();
//RowBounds实现分页
RowBounds rowBounds=new RowBounds(1,2);
rowBounds.getLimit();
//通过java代码层面实现分页
List<User> userList=sqlSession.selectList("com.zwq.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
解溶解
可拓展
提高潜力
注解在接口上实现
@Select("select * from user")
List<User> getUsers();
需要在核心配置文件中绑定接口
<mappers>
<mapper class="com.zwq.dao.UserMapper"/>
</mappers>
测试
本质:反射机制实现
底层:动态代理就是增强真实对象的功能方法
Mybatis详细执行流程
考虑到基础入门阶段,这里暂时不详细叙述源码刨析详解,后续会更新
可以在工具类创建时候实现自动提交事务
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(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=#{id}")
//基本数据类型需要加上参数注解
int deleteUser(@Param("id") 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包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
<scope>provided</scope>
</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
说明:
@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‘);
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--核心配置文件-->
<mapper namespace="com.zwq.dao.StudentMapper">
<!--
1.查询所有学生信息
2.根据查询出来的学生的tid,寻找对应老师
-->
<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
集合 collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
</mapper>
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid, s.name sname, t.name tname from student s,teacher t where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
上述两种查询方式类似于mysql的查询方式
例如:一个老师对应多个学生,对于老师来说,就是一对多的关系
学生实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
老师实体类
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> studentList;
}
<resultMap id="StudentTeacher" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂属性需要单独处理,对象association 集合:collection
javaType="" 指定属性类型
集合中的泛型信息,需要使用ofType获取
-->
<collection property="students" javaType="ArrayList" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<select id="getTeacher" resultMap="StudentTeacher">
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>
<select id="getTeacher2" resultMap="StudentTeacher2">
select * from teacher where id = #{tid}
</select>
<resultMap id="StudentTeacher2" type="Teacher">
<!--此处的javaType对应查询学生类型List-->
<!--此处id是查询出来的老师id传给下面查询学生的sql语句进行映射-->
<collection property="students" ofType="Student" select="getStudentByTeacherId" column="id">
</collection>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student" >
select * from student where tid = #{tid}
</select>
什么是动态SQL:动态SQL就是指根据不同的条件生成不同SQL语句
动态SQL本质上还是SQL,知只是再原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` 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
工程项目
导包
编写配置文件
编写实体类
@Data
public class blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
编写实体类对应Mapper接口和Mapper.xml
<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>
<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 views=#{views}
</otherwise>
</choose>
</where>
</select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。**
<where>
<if test="title != null">
and title=#{title}
</if>
<if test="author !=null">
and author=#{author}
</if>
</where>
<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>
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" separator="or" close=")">
id=#{id}
</foreach>
</where>
</select>
使用SQL标签抽取公共部分
<sql id="if-title-author">
<if test="title != null">
and 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>
注意:
所谓缓存就是在查询数据库的过程中,将查询结果暂时的存放在一个可以直接取到的地方———》内存,当进行再次查询数据的过程中无需重新访问数据库,而是将数据直接从缓存中取出来,减少与数据库的交互
什么是缓存
为什么使用缓存?
什么样的数据能使用缓存?
Mybatis系统默认定义了两级缓存:一级缓存和二级缓存
测试步骤:
开启日志!
测试在一个Session中查询两次相同记录
查看日志输出
@Test
public void queryUserById()
{
SqlSession sqlSession=MybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
User user= mapper.queryUserById(1);
System.out.println(user);
User user1=mapper.queryUserById(1);
System.out.println(user1);
System.out.println(user==user1);
}
缓存失效的情况:
查询不同的东西
删改操作,可能会改变原始数据,所以会刷新缓存
查询不同的Mapper.xml
手动清理缓存
sqlSession.clearCache();
一级缓存默认开启,只在一次Sqlsession中有效,即开启数据库连接到关闭连接
步骤:
开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true "/>
在要使用的二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>
也可以自定义参数
<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
<!--这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。-->
测试
@Test
public 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();
}
小结:
Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存
第三方缓存实现--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资源或出现问题,则将使用默认配置。
<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>```
原文:https://www.cnblogs.com/zwq023/p/14386170.html