Mybatis

Mybatis

Hello Mybatis

配置环境

配置maven项目的pom.xml文件

  1. 配置依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <dependencies>
    <!-- MyBatis依赖 -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.22</version>
    </dependency>
    <!-- mysql数据库连接依赖 -->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
    </dependency>
    </dependencies>
  2. 对于mapper的xml文件找不到问题,需在pom.xml文件中声明下述代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
    <resources>
    <resource>
    <directory>src/main/resources</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>true</filtering>
    </resource>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>true</filtering>
    </resource>
    </resources>
    </build>

创建MyBatis主配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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>
<!--添加日志功能-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--配置数据源:创建连接对象Connection对象-->
<dataSource type="POOLED">
<!--driver:驱动的内容-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/stu?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="xxxxxx"/>
</dataSource>
</environment>
</environments>
<!--
指定其它mapper文件的位置::其它mapper文件的作用是找到其它文件的sql语句
-->
<mappers>
<!--
使用mapper的resource属性指定mapper文件的路径
注:路径是从target/classes路径开始的

使用注意:
resource="mapper文件的路径(使用 / 做分隔)"
一个mapper resource指定一个mapper文件
-->
<!-- <mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
</mappers>
</configuration>

遇到问题:

  • Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 2 字节的 UTF-8 序列的字节 2 无效

    错误原因暂不明;

    解决方法:

    • 删去注释;

    • 在pom文件中加入下面代码或

      1
      2
      3
      <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
  • Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; 前言中不允许有内容

    错误原因:mybatis主配置文件编码问题

    解决方法:用Notepad++进行文件转码成UTF-8

创建MyBatisUtils工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MybatisUtils {

private static String resource = "mybatis-config.xml";
private static InputStream inputStream;
private static SqlSessionFactory sqlSessionFactory;

static {
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}

public static SqlSession getSqlSession() {
if (sqlSessionFactory != null) {
return sqlSessionFactory.openSession();
}
return null;
}
}

编写Mapper接口及xml文件

1
2
3
public interface StudentDao {
Map<String, Object>[] selectAllStudents();
}
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hznu.dao.StudentDao">
<select id="selectAllStudents" resultType="java.util.Map">
select * from student
</select>
</mapper>

编写测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MyTest {
@Test
public void test01() throws IOException {
SqlSession sqlSession = MybatisUtils.getSqlSession();
if (sqlSession != null) {
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
Map<String, Object>[] maps = mapper.selectAllStudents();
for (int i = 0; i < maps.length; i++) {
System.out.println(maps[i]);
}
}
}
}

Mybatis的一些重要对象

  • Resource:负责读取主配置文件
  • SqlSessionFactoryBuilder:负责创建SqlSessionFactory对象
1
2
3
4
5
6
7
8
//基础配置代码

//1、定义mybatis主配置文件的位置,从类路径开始的相对路径
String resource = "mybatis-config.xml";
//2、读取主配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//3、创建SqlSessionFactory对象,
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  • SqlSessionFactory:用于获取SqlSession对象

    特点:

    • 创建的对象是一个重量级对象:创建此对象需要使用更多的资源和时间

      1
      官方文档说明:SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。
    • 是一个接口:是SqlSession的工厂类,用于创建SqlSession对象,DefaultSqlSessionFactory是其实现类

      1
      public class DefaultSqlSessionFactory implements SqlSessionFactory
    • 常用方法:

      1
      2
      3
      4
      5
      //获取一个默认的SQLSession对象,默认手动提交事务
      SqlSession openSession();

      //在上述基础上控制是否自动提交事务
      SqlSession openSession(boolean autoCommit);
  • SqlSession:由SqlSessionFactory对象获取得到,本身为一个接口

    1
    2
    //实现类
    public class DefaultSqlSession implements SqlSession

    作用:提供了大量的执行sql语句的方法

    1
    2
    3
    selectOne:执行sql查询语句,得到最多一行记录,多余1行则报错
    selectList:执行sql查询语句,返回多条记录
    insert/update/delete/commit/rollback:同sql语句

    注:线程不安全,使用步骤:

    1. 在方法内部使用sql前先获取SqlSession对象
    2. 调用SqlSession的方法执行sql语句
    3. 关闭SqlSession

使用动态代理简化

如果我们要使用MyBatis进行数据库操作的话,大致要做两件事情:

  1. 定义dao接口文件:在dao接口中定义需要进行的数据库操作方法;
  2. 创建映射文件:当有了dao接口后,还需要为该接口创建映射文件,映射文件中定义了一系列SQL语句,这些SQL语句和dao接口一一对应;

MyBatis在初始化的时候会将映射文件与dao接口一一对应,并根据映射文件的内容为每个函数创建相应的数据库操作能力。而我们作为MyBatis使用者,只需将dao接口注入给Service层使用即可。
那么MyBatis是如何根据映射文件为每个dao接口创建具体实现的?答案是——动态代理。

1
StudentDao dao = session.getMapper(StudentDao.class);  //Mybatis通过代理生成dao接口的实现类

用法:

1
2
3
4
5
6
7
//使用代理技术完成简单使用Mybatis
try (SqlSession session = MybatisUtils.getSqlSession()) {
StudentDao dao = session.getMapper(StudentDao.class);
int n = dao.insertStudent(new Student("95008", "Jack Ma", "1", 55, "CS"));
session.commit();
System.out.println("影响" + n + "条数据");
}

占位符

  • #占位符,推荐使用。

    语法:#{字符}

    Mybatis处理#{字符}使用的是jdbc的PrepareStatment对象。

    特点:

    • 执行sql语句效率高;
    • 保证安全性,防注入;
    • 常常作为列值使用,位于等号的右侧,其值和数据类型相关。
  • $占位符,使用基本与#占位符相同

    语法:${字符}

    Mybatis处理${字符}使用的是jdbc的Statment对象。

    常常作为表名或列名使用,在能保证数据安全的情况下使用该占位符。

    使用地方:如order排序时

MyBatis配置

1、mybatis-config.xml,MyBatis核心配置文件

注意不同标签插入的顺序有要求,必须依照下述顺序

1
2
(properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, 
reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>

1)properties(属性),引入外部配置文件

1
2
3
4
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/stu?serverTimezone=GMT%2B8
username = root
password = 123456
1
2
3
4
5
6
7
8
9
10
11
12
<properties resource="db.properties"/>

<!-- 等价于,即可自定义属性 -->
<properties>
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/stu?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="xxxxxxx"/>
</properties>

<!-- 使用属性 -->
<property name="driver" value="${driver}"/>

注:对于外部引入properties属性与配置文件中自定义属性同名的,外部引入的属性优先级更高,优先使用外部引入属性。

2)typeAliases(类型别名)

  1. 类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

    1
    2
    3
    <typeAliases>
    <typeAlias alias="Author" type="domain.blog.Author"/>
    </typeAliases>

    当这样配置时,Blog 可以用在任何使用 domain.blog.Blog 的地方。

  2. 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

    1
    2
    3
    <typeAliases>
    <package name="domain.blog"/>
    </typeAliases>
  3. 每一个在包 domain.blog 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author 的别名为 author;若有注解,则别名为其注解值。见下面的例子:

    1
    2
    3
    @Alias("author")
    public class Author {
    }

4)设置(settings)

设置名 描述 有效值 默认值
mapUnderscoreToCamelCase 是否开启驼峰命名自动映射,即从经典数据库列名A_COLUMN映射到经典Java属性名aColumn true false
logImpl 指定MyBatis所用日志的具体实现,未指定时将自动查找。 LOG4J STDOUT_LOGGING
cacheEnabled 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 true false
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。 true false
日志实现——log4j

apache开源的一个日志实现。

简单使用
  1. 在要使用Log4j 的类中,导入包import org.apache.log4j.Logger;

  2. 日志对象,参数为当前类的class

    1
    static Logger logger = Logger.getLogger(UserDaoTest.class);
  3. 日志级别

    1
    2
    3
    logger.info("info:进入了testLog4j");
    logger.debug("debug:进入了testLog4j");
    logger.error("error:进入了testLog4j");
MyBatis中使用步骤:
  1. 先导入具体jar包

    1
    2
    3
    4
    5
    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    </dependency>
  2. 在resource目录下创建log4j.properties配置文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    #将等级为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. 在mybatis-config.xml主配置文件中设置日志实现未log4j

    1
    2
    3
    4
     <!--添加日志功能-->
    <settings>
    <setting name="logImpl" value="LOG4J"/>
    </settings>

5)映射器(mappers)

引入Mapper文件

1
2
3
4
5
6
7
8
9
10
11
12
<mappers>
<!-- 此方式下找到mapper文件即可 -->
<mapper resource="cn/hznu/dao/StudentMapper.xml"/>

<!--
这两种方法要求接口与xml文件在同一目录下,且文件名相同
-->
<!-- 引入某个接口对应的mapper -->
<mapper class="cn.hznu.dao.StudentMapper"/>
<!-- 引入一个包中所有mapper -->
<package name="cn.hznu.dao"/>
</mappers>

resultMap,结果集映射

用于解决实体类属性名与数据库表字段名不匹配问题。

属性的对应关系:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!-- id表示此resultMap的id,用于之后sql语句中引用,type表示Java实体类 -->
<resultMap id="studentMap" type="cn.hznu.domain.Student">
<!-- 主要用于主键字段,其余与result作用相同 -->
<id column="Sno" property="sno"/>
<!-- 主要用于非主键字段,其余与id作用相同 -->
<result column="Sname" property="name"/>
<result column="Ssex" property="sex"/>
<result column="Sage" property="age"/>
<result column="Sdept" property="dept"/>

<!--
association,用于引用类型属性的对应关系,主要用于表连接
比如说 一个学生所选修的课程中成绩最高的课程(假设没有重分情况)
在学生实体类中存在一个变量Course记录其对应课程信息
-->
<association property="bestCourse" javaType="cn.hznu.domain.Course">
<id column="Cno" property="cno"/>
<result column="Cname" property="cname"/>
<result column="Cpon" property="cpon"/>
<result column="Ccredit" property="ccredit"/>
</association>

<!-- 对于数据库中的一对多关系,比如查询一个学生选修的所有课程信息 -->
</resultMap>

<!--
对于association的另一个用法:
用于将单表中的一个字段映射成一个表的所有属性,比如查找sc关系表当前行对应的课程信息,则可用类子查询的转换,具体sql如下
-->

<!-- 两个普通子查询 -->
<select id="selectStudent" resultMap="studentMap">
select * from student where Sno = #{sno}
</select>

<select id="selectCourse" resultMap="courseMap">
select * from course where Cno = #{cno}
</select>

<!-- 结果集映射 -->
<resultMap id="SCMap" type="cn.hznu.domain.SC">
<id column="Cno" property="cno"/>
<id column="Sno" property="sno"/>

<result column="Grade" property="grade"/>

<!-- 属性对应关系 -->
<association property="student" column="sno" javaType="cn.hznu.domain.Student" select="selectStudent"/>
<association property="course" column="cno" javaType="cn.hznu.domain.Course" select="selectCourse"/>
</resultMap>

<!-- 查询语句 -->
<select id="selectDetailInfo" resultMap="SCMap">
select *
from (student natural join sc) natural join course
</select>

<!--
对于一对多关系的查询,其结果集映射可食用collection标签
-->
<resultMap id="studentMap" type="cn.hznu.domain.Student">
............
<!-- 注意:这里使用的映射Java类型使用的属性为 ofType,这是由于该项属性为集合类型如List,这里的ofType代表泛型 -->
<collection property="courses" ofType="cn.hznu.domain.Course">
<id column="Cno" property="cno"/>

<result column="Cname" property="cname"/>
<result column="Cpon" property="cpon"/>
<result column="Ccredit" property="ccredit"/>
</collection>
</resultMap>

<!-- 查询某学生选修的所有课程,所有课程为一个集合列表 private List<Course> courses; 存储在Student实体类中 -->
<select id="findAllMyCourses" resultMap="studentMap">
select *
from (student natural join sc) natural join course
where Sno = #{sno}
</select>

<!-- 对于collection的另一个用法:类似上述association -->
<!-- 先查找出对应的学生 -->
<select id="findAllMyCoursesOther" resultMap="studentMapOther">
select *
from student
where Sno = #{sno}
</select>

<resultMap id="studentMapOther" type="cn.hznu.domain.Student">
............
<!-- 传递sno到子查询中,查找出所有课程然后放入对应属性中 -->
<collection property="courses" javaType="ArrayList" ofType="cn.hznu.domain.Course" column="Sno" select="selectCourses"/>
</resultMap>

<select id="selectCourses" resultMap="courseMap">
select Cno, Cname, Cpno, Grade
from sc natural join course
where sc.Sno = #{sno}
</select>

案例:

具体解决再上述xml代码中已经说明。

  1. 查找学号为95001的学生所选修的课程中成绩最高的课程。
  2. 查找学号为95001的学生选修的所有课程。

动态sql

在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

if标签

1
2
3
4
5
6
7
8
<select id="selectDetailInfoIf" resultMap="SCMap">
select *
from (student natural join sc) natural join course
where 1 = 1
<if test="sdept != null"> <!-- 其中sdept是传入的参数,其余的为固定语法 -->
and Sdept = #{sdept}
</if>
</select>

使用注解开发

Lombok

插件工具,用于简化简单实体类的创建。

主要使用其注解,包含如下注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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

使用步骤;

  1. 在IDEA中下载插件Lombok

  2. 导入对应依赖

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.18</version>
    </dependency>
  3. 在实体类中使用,作用域为类

常用注解详解:

  • @Data:用于生产实体类的无参构造方法Getter/Setter方法toString方法hasCode方法equals等基础方法;
  • @RequiredArgsConstructor:创建有参构造方法
  • @NoArgsConstructor:创建无参构造方法
  • @EqualsAndHashCode@ToString@Getter@Setter

缓存

简介

1
2
3
4
查询  :  连接数据库 ,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方!--> 内存 : 缓存

我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
  1. 什么是缓存 [ Cache ]?
    • 存在内存中的临时数据。
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
  2. 为什么使用缓存?

    • 减少和数据库的交互次数,减少系统开销,提高系统效率。
  3. 什么样的数据能使用缓存?

    • 经常查询并且不经常改变的数据。【可以使用缓存】

Mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

  • MyBatis系统中默认定义了两级缓存:一级缓存二级缓存

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)

    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。

    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

一级缓存

  • 一级缓存也叫本地缓存: SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

测试步骤:

  1. 开启日志!
  2. 测试在一个Sesion中查询两次相同记录
  3. 查看日志输出

1569983650437

缓存失效的情况:

  1. 查询不同的东西

  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!

    1569983952321

  3. 查询不同的Mapper.xml

  4. 手动清理缓存!

    1569984008824

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!

一级缓存就是一个Map。

二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

步骤:

  1. 开启全局缓存

    1
    2
    <!--显示的开启全局缓存-->
    <setting name="cacheEnabled" value="true"/>
  2. 在要使用二级缓存的Mapper中开启

    1
    2
    <!--在当前Mapper.xml中使用二级缓存-->
    <cache/>

    也可以自定义参数

    1
    2
    3
    4
    5
    <!--在当前Mapper.xml中使用二级缓存-->
    <cache eviction="FIFO"
    flushInterval="60000"
    size="512"
    readOnly="true"/>
  3. 测试

    1. 问题:我们需要将实体类序列化!否则就会报错!

      1
      Caused by: java.io.NotSerializableException: com.kuang.pojo.User

小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中;
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!

缓存原理

缓存原理

自定义缓存-ehcache

1
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

要在程序中使用ehcache,先要导包!

1
2
3
4
5
6
<!-- 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中指定使用我们的ehcache缓存实现!

1
2
<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

ehcache.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?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>

Redis数据库来做缓存! K-V

数据库环境

测试环境:学生选课数据库,学生表student、课程表实体表course,为多对多关系——即一门课可被多个学生选择/一个学生可选择多门课,该关系对应关系表sc,在course课程表中,存在一对多关系,每门课可以有前置课程(无前置课程Cpno为null),而一门课可为多门课的前置课程,具体ER图如下。

stu

脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

CREATE SCHEMA IF NOT EXISTS `stu` DEFAULT CHARACTER SET utf8 ;
USE `stu` ;

-- -----------------------------------------------------
-- Table `stu`.`course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `stu`.`course` (
`Cno` VARCHAR(5) NOT NULL,
`Cname` VARCHAR(30) NOT NULL,
`Cpno` VARCHAR(5) NULL DEFAULT NULL,
`Ccredit` DECIMAL(2,0) NULL DEFAULT NULL,
PRIMARY KEY (`Cno`),
INDEX `fk01_idx` (`Cpno` ASC) VISIBLE,
CONSTRAINT `fk01`
FOREIGN KEY (`Cpno`)
REFERENCES `stu`.`course` (`Cno`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

LOCK TABLES `course` WRITE;
INSERT INTO `course` VALUES ('1','database','5',4),('2','math',NULL,2),('3','information system','1',4),('4','opreration system','5',3),('5','database structure','2',4);
UNLOCK TABLES;

-- -----------------------------------------------------
-- Table `stu`.`student`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `stu`.`student` (
`Sno` CHAR(5) NOT NULL,
`Sname` VARCHAR(20) NOT NULL,
`Ssex` CHAR(2) NULL DEFAULT NULL,
`Sage` TINYINT(4) NULL DEFAULT NULL,
`Sdept` VARCHAR(10) NULL DEFAULT NULL,
PRIMARY KEY (`Sno`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

LOCK TABLES `student` WRITE;
INSERT INTO `student` VALUES ('95001','Yong Li','1',20,'CS'),('95002','Chen Liu','0',19,'IS'),('95003','Min Wang','0',18,'MA'),('95004','Li Zhang','1',19,'IS'),('95005','Yong Zhang','0',21,'CS'),('95006','Qiu Han','1',28,'CS'),('95007','Chen Chen','1',19,'IS'),('95008','Jack Ma','1',55,'CS');
UNLOCK TABLES;

-- -----------------------------------------------------
-- Table `stu`.`sc`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `stu`.`sc` (
`Sno` CHAR(5) NOT NULL,
`Cno` VARCHAR(5) NOT NULL,
`Grade` DECIMAL(3,0) NULL DEFAULT NULL,
PRIMARY KEY (`Sno`, `Cno`),
INDEX `Cno` (`Cno` ASC) VISIBLE,
CONSTRAINT `sc_ibfk_1`
FOREIGN KEY (`Sno`)
REFERENCES `stu`.`student` (`Sno`),
CONSTRAINT `sc_ibfk_2`
FOREIGN KEY (`Cno`)
REFERENCES `stu`.`course` (`Cno`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

LOCK TABLES `sc` WRITE;
INSERT INTO `sc` VALUES ('95001','1',92),('95001','2',85),('95001','3',88),('95001','4',70),('95002','2',90),('95002','3',80),('95002','4',70),('95003','1',NULL),('95003','3',70);
UNLOCK TABLES;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;