文章目录
MyBatis
环境
- JDK 1.8
- Mysql 5.7
- maven 3.6.1(本机3.6.3)
- IDEA
回顾:
- JDBC
- Mysql
- Java基础
- Maven
- Junit
框架:配置文件 --> 看官网文档
1 简介
1.1 什么是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仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
- Github:https://github.com/mybatis/mybatis-3/releases
- 中文文档:https://mybatis.org/mybatis-3/zh/index.html
1.2 持久化
数据持久化:
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(jdbc),IO文件持久化。
为什么需要持久化?
- 有一些对象,不能让他丢掉。
- 内存太贵了
1.3 持久层
Dao层,Service层,Controller层…
- 完成持久化工作的代码块
- 层的界限十分明显
1.4 为什么需要MyBatis?
-
帮助程序员把数据存入到数据库中
-
方便
-
传统的JDBC代码太复杂——简化——框架——自动化
-
不用MyBatis也可以,有了MyBatis更容易上手——技术没有高低之分
-
优点
-
简单易学
灵活
sql和代码的分离,提高了可维护性
提供映射标签,支持对象与数据库的orm字段关系映射
提供对象关系映射标签,支持对象关系组建维护
提供xml标签,支持编写动态sql
-
使用人多
2 第一个MyBatis程序
思路:搭建环境——导入MyBatis——编写代码——测试
2.1 搭建环境
- 搭建数据库
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, '春阳', '123458'),
(3, '秋阳', '123457')
- 新建项目
新建一个普通的Maven项目,删除src目录,作为父工程,导入Maven依赖
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--MyBatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/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>
2.2 创建一个Maven模块
- 编写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>
</configuration>
- 编写Mybatis工具类
// SqlSessionFactory SqlSession
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 1.使用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 命令所需的所有方法。
public static SqlSession getSqlSession() {
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
return sqlSessionFactory.openSession();
}
}
2.3 编写代码
- 实体类
package com.GrandNovice.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.GrandNovice.dao;
import com.GrandNovice.pojo.User;
import java.util.List;
// UserDao的实现类UserDaoImpl不再需要,取而代之的配置文件
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">
<!--namespace=绑定一个对应的Dao/Mapper接口,相当于原来对应接口的实现类-->
<mapper namespace="com.GrandNovice.dao.UserDao">
<!--select查询语句
id对应原来的方法名(接口中的抽象方法名/本应该在实现类中重写的方法名)
resultType方法返回结果类型
-->
<select id="getUserList" resultType="com.GrandNovice.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.4 测试(junit)
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.GrandNovice.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册mappers
- junit测试
package com.GrandNovice.dao;
import com.GrandNovice.pojo.User;
import com.GrandNovice.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test() {
// 获得SqlSession对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
// 方式1 getMapper
// 执行sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
// 关闭sqlSession
sqlSession.close();
}
}
可能会遇到的问题:
- 配置文件没有注册
<!--每一个Mapper.xml都需要在Mybatis核心配置文件mybatis-config.xml中注册-->
<mappers>
<mapper resource="com/GrandNovice/dao/UserMapper.xml"/>
</mappers>
- 绑定接口错误
- 方法名不对
- 返回类型不对
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">
<!--namespace=绑定一个对应的Dao/Mapper接口,相当于原来对应接口的实现类-->
<mapper namespace="com.GrandNovice.dao.UserDao">
<!--select查询语句
id对应原来的方法名(接口中的抽象方法名/本应该在实现类中重写的方法名)
resultType方法返回结果类型
-->
<select id="getUserList" resultType="com.GrandNovice.pojo.User">
select * from mybatis.user
</select>
</mapper>
- Maven导出资源问题
两个pom.xml文件
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
从左到右按顺序写
3 CRUD
3.1、namespace
namespace中的报名要和Dao/Mapper接口中的包名一致
3.2、select
选择,查询语句
- id:对应的namespace中的方法名
- resultType:sql语句执行的返回值
- parameterType:namespace中的方法的参数类型
- 编写接口
// 根据id查询用户
User getUserById(int id);
- 编写对应的Mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.GrandNovice.pojo.User">
select * from mybatis.user where id = #{id};
</select>
- 测试
@Test
public void test_getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
3.3、insert
<!--对象中的属性可以直接取出来-->
<insert id="addUser" parameterType="com.GrandNovice.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd});
</insert>
3.4、update
<!--set后面的属性写几个,就会修改几个-->
<update id="updateUser" parameterType="com.GrandNovice.pojo.User">
update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id};
</update>
3.5、delete
<!--parameterType="int"可省略-->
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
注意点:
增删改需要提交事务!
3.6、分析错误
3.7、Map
假设我们的实体类,或者数据库中的表字段或参数过多,我们应当考虑使用Map
UserMapper接口
// 使用Map 不需要知道数据库里有什么字段,只需要去查即可
int addUser2(Map<String, Object> map);
UserMapper.xml
<!--添加用户
传递Map的key-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id, name, pwd) values (#{userid}, #{username}, #{password});
</insert>
@Test
public void test_addUser2() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid", 6);
map.put("username", "黄蜂");
map.put("password", "123321");
int res = mapper.addUser2(map);
if (res > 0) {
System.out.println("插入成功");
}
// 提交事务
sqlSession.commit();
// 关闭
sqlSession.close();
}
Map传递参数直接在sql中取出key即可(key可以随意定义)parameterType=“map”
对象传递参数要在sql中取出对象的属性(属性名同数据库一致)parameterType=“Object”
只有一个基本类型参数情况下,可以直接在sql中取。parameterType=""(不写)
多个参数用Map,或者注解
8、模糊查询(防止sql注入)
- java代码执行的时候,传递通配符% %
List<User> userList = userMapper.getUserLike("%阳");
- 在sql拼接中使用通配符! like “%”#{value};
select * from mybatis.user where name like "%"#{value}"%";
// 或者
select * from mybatis.user where name like concat('%', #{value}, '%');
4 配置解析
4.1 核心配置文件
- mybatis-config.xml
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
4.2 环境配置(environments)
MyBatis 可以配置成适应多种环境。
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会使用配置多套运行环境,通过在environments中的default选择环境id进行操作
MyBatis默认:
事务管理器:JDBC
两种类型的事务管理器(type="[JDBC|MANAGED]")
数据源连接池默认:POOLED
三种内建的数据源类型(type="[UNPOOLED|POOLED|JNDI]")
4.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=123456
在核心配置文件中引入
<!--引入外部配置文件-->
<properties resource="db.properties">
<!--也可以username,password不在配置文件中写,在这里用键值对的形式添加-->
<property name="username" value="root"/>
<property name="pwd" value="111111"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一字段,优先使用外部配置文件的
4.4 类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字。
- 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
例:com.GrandNovice.pojo.User→User
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.GrandNovice.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写
例:com.GrandNovice.pojo.User→user
<!--可以用包的方式给实体类起别名-->
<typeAliases>
<package name="com.GrandNovice.pojo"/>
</typeAliases>
在实体类比较少的时候,建议使用第一种方式
如果实体类比较多,建议使用第二种方式
第一种方式可以随意DIY,第二种不可以,在使用注解的情况下可以DIY
需要在实体类添加注解,修改类的别名
// 利用注解起别名
// 需要在XML文件中通过注解标签中的属性package指定包名,如果这里没有通过注解命名,则对应类名为User,如果这里起了别名,则对应别名为这里的别名(此处为hello)
@Alias("hello")
public class User {}
UserMapper.xml中
<select id="getUserList" resultType="hello">
select * from mybatis.user;
</select>
4.5 设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
4.6 其他配置(了解)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
mybatis-generator-core
mybatis-plus
通用Mapper - 映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件;
方式一:
<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/GrandNovice/dao/UserMapper.xml"/>
</mappers>
方式二:使用映射器接口实现类的完全限定类名
注意点:
- 接口和Mapper配置文件必须同名
- 接口和Mapper配置文件必须在同一个包下
<mappers>
<!--方式一-->
<!-- <mapper resource="com/GrandNovice/dao/UserMapper.xml"/>-->
<!--方式二-->
<mapper class="com.GrandNovice.dao.UserMapper"/>
</mappers>
方式三:使用扫描包进行注入绑定
将包内的映射器接口实现全部注册为映射器
注意点:
- 接口和Mapper配置文件必须同名
- 接口和Mapper配置文件必须在同一个包下
<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<!--方式一:使用相对于类路径的资源引用-->
<!-- <mapper resource="com/GrandNovice/dao/UserMapper.xml"/>-->
<!--方式二:使用映射器接口实现类的完全限定类名-->
<!-- <mapper class="com.GrandNovice.dao.UserMapper"/>-->
<!-- 方式三:将包内的映射器接口实现全部注册为映射器 -->
<package name="com.GrandNovice.dao"/>
</mappers>
4.7 作用域(Scope)和生命周期
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了——局部变量
SqlSessionFactory:
- 可以理解为数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- 多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。——程序开始即开始,程序结束才结束
- 最简单的就是使用单例模式或者静态单例模式。
SqlSession:
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要赶紧关闭
这里面的每一个Mapper,就代表一个具体的业务。
5 解决属性名和字段名不一致的问题
5.1 问题
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况(将实体类中的属性pwd改成password)。
package com.GrandNovice.pojo;
import org.apache.ibatis.type.Alias;
// 利用注解起别名
@Alias("hello")
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
select * from mybatis.user where id = #{id};
// 类型处理器
select id, name, pwd from mybatis.user where id = #{id};
解决方法:
- 起别名
<select id="getUserById" parameterType="int" resultType="User">
select id, name, pwd as password from mybatis.user where id = #{id};
</select>
5.2 resultMap
结果集映射
id name pwd
id name password
<!--结果集映射-->
<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" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id = #{id};
</select>
- resultMap 元素是 MyBatis 中最重要最强大的元素。
- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
- ResultMap 的优秀之处——你完全可以不用显式地配置它们。
6 日志
6.1 日志工厂
如果一个数据库操作出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout debug
- SLF4J
- LOG4J [掌握]
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING [掌握]
- NO_LOGGING
在MyBatis中具体使用哪一个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
在MyBatis核心配置文件中,配置我们的日志。
<settings>
<!--标准的日志工厂设置-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2 LOG4J
什么是LOG4J?
- Log4J是Apache的一个开源项目,通过使用Log4J,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
- 导入LOG4J的包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</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
1og4j.appender.file.File=./log/MRX.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-MN-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sq1=DEBUG
log4j.logger.java.sq1.statement=DEBUG
log4j.logger.java.sq1.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
- 配置LOG4J为日志实现方式
<settings>
<!--标准的日志工厂设置-->
<!-- <setting name="logImpl" value="STDOUT_LOGGING"/>-->
<setting name="logImpl" value="LOG4J"/>
</settings>
4.LOG4J的使用,单元测试
简单使用
- 导包import org.apache.log4j.Logger;
- 日志对象,参数为当前类的.class
static Logger logger = Logger.getLogger(UserDaoTest.class);
- 日志级别
logger.info("info:进入了test_log4j()方法" );
logger.debug("debug:进入了test_log4j()方法");
logger.error("error:进入了test_log4j()方法");
7 分页
为什么要分页?
- 减少数据的处理量(提高效率)
7.1 SQL使用limit分页
select * from user limit startIndex, pageSize;
select * from user limit 3; # [0, 3]
使用MyBatis实现分页,核心SQL
- 接口
// 分页 者少需要两个参数startIndex和pageSize
// 这里选择使用Map实现
List<User> getUserByLimit(Map<String, Integer> map);
- Mapper.xml
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--
column数据库中的字段
property实体类中的属性
-->
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex}, #{pageSize};
</select>
3.测试
@Test
public void test_getUserByLimit() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex", 0);
map.put("pageSize", 2);
List<User> userByLimit = mapper.getUserByLimit(map);
for (User user : userByLimit) {
System.out.println(user);
}
sqlSession.close();
}
7.2 RowBounds分页
不再使用SQL实现分页
- 接口
List<User> getUserByRowBounds(Map<String, Integer> map);
- Mapper.xml
<!--RowBounds分页-->
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
- 测试
@Test
public void test_getUserByRowBounds() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
// RowBounds实现分页
RowBounds rowBounds = new RowBounds(1, 2);
// 通过java代码层面实现分页
List<User> userList = sqlSession.selectList("com.GrandNovice.dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
7.3 分页插件
8 使用注解开发
8.1 面向接口编程
- 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
- 根本原因︰解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
- 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现的,对系统设计人员来讲就不那么重要了;
- 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
- 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
- 接口的本身反映了系统设计人员对系统的抽象理解。
- 接口应有两类:
- 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
- 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface) ;
- 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构
8.2 使用注解开发
- 注解直接在接口上实现
@Select("select * from user")
List<User> getUsers();
- 需要在核心配置文件mybatis-config.xml文件中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="com.GrandNovice.dao.UserMapper"/>
</mappers>
- 测试
@Test
public void test_getUsers() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 底层主要应用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
MyBatis详细的执行流程
8.3 CRUD
可以在创建工具类的时候实现自动提交事务
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
// 方法存在多个参数,所有的参数前面必须加上@Param注解,注解参数命名跟#{}内的名称一致
@Select("select * from user where id = #{id} and 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);
}
测试类[我们必须要将接口注册绑定到我们的核心配置文件中!]
public class UserMapperTest {
@Test
public void test_getUsers() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 底层主要应用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test_getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1, "冬阳");
System.out.println(user);
sqlSession.close();
}
@Test
public void test_addUser() throws Exception{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5, "光辉", "123321"));
sqlSession.close();
}
@Test
public void test_updateUser() throws Exception{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4, "夏阳", "121212"));
sqlSession.close();
}
@Test
public void test_deleteUser() throws Exception{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(5);
sqlSession.close();
}
}
关于@Param()注解
- 基本类型的参数或者String类型需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
- @Param()中设定的属性名称就是SQL语句中 #{} 内的名称
#{}和${}区别:
区别:
- #方式能够很大程度防止sql注入,$方式无法防止Sql注入。
- $方式一般用于传入数据库对象,例如传入表名。
- 从安全性上考虑,能使用#尽量使用#来传参,因为这样可以有效防止SQL注入的问题。
- 注意:MyBatis排序时使用order by 动态参数时需要注意,用$而不是#!
9 Lombok
Lombok是一款Java开发插件,使得Java开发者可以通过其定义的一些注解来消除业务工程中冗长和繁琐的代码,尤其对于简单的Java模型对象(POJO)。在开发环境中使用Lombok插件后,Java开发人员可以节省出重复构建,诸如hashCode和equals这样的方法以及各种业务对象模型的accessor和ToString等方法的大量时间。对于这些方法,它能够在编译源代码期间自动帮我们生成这些方法,并没有如反射那样降低程序的性能。
- 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的包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</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
@Data:无参构造,get,set,toString,hashcode,equals
@Data // 无参构造,get,set,toString,hashcode,equals
@AllArgsConstructor // 有参构造(使用了这个和Data,Data中的无参构造会消失)
@NoArgsConstructor // 无参构造
- 在实体类上加注解即可
package com.GrandNovice.pojo;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
Lombok的优缺点
优点:
- 能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定的开发效率
- 让代码变得简洁,不用过多的去关注相应的方法
- 属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等
缺点:
- 不支持多种参数构造器的重载
- 虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度
总结
- Lombok虽然有很多优点,但Lombok更类似于一种IDE插件,项目也需要依赖相应的jar包。Lombok依赖jar包是因为编译时要用它的注解,为什么说它又类似插件?因为在使用时,eclipse或Intelli IDEA都需要安装相应的插件,在编译器编译时通过操作AST(抽象语法树)改变字节码生成,变向的就是说它在改变java语法。
- 它不像spring的依赖注入或者mybatis的ORM一样是运行时的特性,而是编译时的特性。这里我个人最感觉不爽的地方就是对插件的依赖!因为Lombok只是省去了一些人工生成代码的麻烦,但IDE都有快捷键来协助生成getter/setter等方法,也非常方便。
知乎上有位大神发表过对Lombok的一些看法:
这是一种低级趣味的插件,不建议使用。AVA发展到今天,各种插件层出不穷,如何甄别各种插件的优劣?能从架构上优化你的设计的,能提高应用程序性能的,实现高度封装可扩展的…,像lombok这种,像这种插件,已经不仅仅是插件了,改变了你如何编写源码,事实上,少去了的代码你写上去又如何?如果JAVA家族到处充斥这样的东西,那只不过是一坨披着金属颜色的屎,迟早会被其它的语言取代。
虽然话糙但理确实不糙,试想一个项目有非常多类似Lombok这样的插件,个人觉得真的会极大的降低阅读源代码的舒适度。虽然非常不建议在属性的getter/setter写一些业务代码,但在多年项目的实战中,有时通过给getter/setter加一点点业务代码,能极大的简化某些业务场景的代码。所谓取舍,也许就是这时的舍弃一定的规范,取得极大的方便。
我现在非常坚信一条理念,任何编程语言或插件,都仅仅只是工具而已,即使工具再强大也在于用的人,就如同小米加步枪照样能赢飞机大炮的道理一样。结合具体业务场景和项目实际情况,无需一味追求高大上的技术,适合的才是王道。
Lombok有它的得天独厚的优点,也有它避之不及的缺点,熟知其优缺点,在实战中灵活运用才是王道。
10 多对一处理
多个学生对应一个老师
——对于学生而言,多个学生关联一个老师
——对于老师而言,一个老师有很多学生 【集合】
SQL:
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;`teacher``student`
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');
10.1 测试环境搭建
-
导入lombok
-
新建实体类Student Teacher
-
建立Mapper接口
-
建立Mapper.xml文件(多个文件建议建在同路径的resources下,这样可以在target中合并生成)
-
在mybatis-config.xml中注册Mapper接口或者注册路径
-
测试
10.2 按照查询嵌套处理
<!--按照查询嵌套处理——子查询-->
<!--思路
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,对象类型javaType,通过column要执行什么操作select-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{tid}
</select>
10.3 按照结果嵌套处理
<!--按照结果嵌套处理——联表查询-->
<!--思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师
-->
<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">
<!--起了别名后,对应的column为对应的别名的名字-->
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
回顾MySQL多对一查询方式:
- 子查询
- 联表查询
11 一对多处理
一个老师拥有多个学生,对于老师而言,就是一对多关系
11.1 环境搭建
实体类
package com.GrandNovice.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
package com.GrandNovice.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
// 一个老师拥有多个学生
private List<Student> students;
}
11.2 按照结果嵌套处理(联合查询)
<!--====================推荐下面这种方式========================-->
<!--按照结果嵌套查询-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select s.id sid, s.name sname, t.id tid, t.name tname
from student s, teacher t
where s.tid = t.id and t.id = #{tid};
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--一个老师拥有多个学生private List<Student> students;
这里需要使用集合collection
javaType:指定属性的类型
List<Student>:对于这种集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
11.3 按照查询嵌套处理(子查询)
<!--=================下面为子查询 不推荐使用(复杂)===========================-->
<select id="getTeacher1" resultMap="TeacherStudent1">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent1" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid = #{tid}
</select>
小结
-
关联——association 【多对一】
-
集合——collection 【一对多】
-
javaType & ofType
javaType用来指定实体类中属性的类型
ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型 -
不好理解!!!
注意点
- 保证SQL的可读性,尽量保证通俗易懂
- 尽量保证一对多和多对一中属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用log4j
面试高频:
- MySQL引擎
- INNODB底层原理
- 索引
- 索引优化
12 动态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
创建一个基础工程
- 导包
- 编写配置文件
- 编写实体类
package com.GrandNovice.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime; // 下划线命名改驼峰命名导致属性名和字段名不一致
private int views;
}
mybatis-config.xml中设置
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
<!--开启驼峰命名转换-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
- 编写实体类对应的Mapper接口和Mapper.xml文件
IF
- 接口
// 查询博客
List<Blog> queryBlogIF(Map map);
- xml
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog where 1 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
- 测试
@Test
public void test_queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title", "胜利");
map.put("author", "阿梨");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.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>
trim(where, set)
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
set 元素会动态地在行首插入 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>
可以通过自定义 trim 元素来定制功能。
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码。
SQL片段
有时候我们会将一些公共部分抽取出来方便复用!
- 使用SQL标签抽取公共的部分
- 在需要使用的地方使用include标签通过id引用即可
<!--抽取公共SQL-->
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<!--引用公共SQL-->
<include refid="if-title-author"></include>
</where>
</select>
SQL片段注意事项:
- 最好基于单表来定义SQL片段
- 不要存在where标签
Foreach
<!--为了拼接下面这句SQL
select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
使用了where标签后,and就没有了,因此不用加在前缀上
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<!--我们现在传递一个Map,Map中存储一个集合-->
<foreach collection="ids" item="id"
open="(" separator="or" close=")">
id = #{id}
</foreach>
</where>
</select>
@Test
public void test_queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids", ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
总结:
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
- 先在MySQL中写完SQL语句,再对应修改xml中的代码
练习:24道实战SQL
13 缓存
13.1 简介
1.什么是缓存[Cache ]?
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
2.为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
3.什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
13.2 Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,指SqlSession从创建到close,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
13.3 一级缓存
- 一级缓存也叫本地缓存:
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试步骤:
- 开启日志
- 测试在一个Session中查询两次相同的记录
- 查看日志输出
缓存失效的情况:
-
查询不同的东西
-
增删改操作可能会改变原来的数据,所以必定会刷新缓存!
- 查询不同的Mapper
- 手动清理缓存
@Test
public void test_queryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.queryUserById(1);
System.out.println(user1);
System.out.println("--------------------------");
// 中间加一个修改用户的语句
// mapper.updateUser(new User(3, "秋香", "123333"));
// System.out.println("--------------------------");
sqlSession.clearCache(); // 手动清理缓存
User user2 = mapper.queryUserById(1);
System.out.println(user2);
System.out.println("user1=user2? " + (user1==user2));
sqlSession.close();
}
小结:
- 一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!
- 一级缓存就是一个Map!
13.4 二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中;
步骤:
- 开启全局缓存
<!--显式开启二级(全局)缓存(默认为true开启)-->
<setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存的Mapper中开启
<!--在当前xml中开启二级缓存,不加任何标签则使用默认配置,也可以添加标签设置属性配置-->
<cache/>
也可以自定义参数
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
- 测试(有时需要将实体类序列化)
@Test
public void test_SecondaryCache(){
SqlSession sqlSession1 = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 = mapper1.queryUserById(1);
System.out.println(user1);
sqlSession1.close(); // 一级缓存结束,缓存丢给二级缓存
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.queryUserById(1);
System.out.println(user2);
System.out.println("user1=user2? " + (user1==user2));
sqlSession2.close();
}
不提前关闭SqlSession1时,没有触发二级缓存,所以使用一级缓存会查询两次
提前关闭SqlSession1,一级缓存结束,缓存丢给二级缓存保持,可以继续缓存,再次查询时直接读取
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中,只有当会话关闭的时候才会提交到二级缓存中
13.6 自定义缓存——ehcache
Ehcache是一种广泛使用的开源ava分布式缓存,主要面向通用缓存
要在程序中使用ehcache,首先要导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
在mapper中指定使用我们的ehcache缓存实现!
配置文件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="java.io./tmpdir/Tmp_EhCache"/>
<!--
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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<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>
Redis数据库来做缓存 Key——Values