陣列與排序及工具類(Arrays類)
Mybatis
結合Mybatis中文文件學習:https://mybatis.org/mybatis-3/zh/index.html
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.4.6</version> </dependency>
-
GitHub:
2、第一個Mybatis
2.1、搭建環境
建立一個普通的maven專案,在裡面再建立一個普通的maven子專案。
匯入依賴
<dependencies> <!-- Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
2.2、編寫JDBC配置檔案
<?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"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?character=UTF-8&useUnicode=true&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
2.3、編寫工具類
package com.Lv.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* @Author: Lv
* @Description:工具類
* @Vision: 1.0
* @Date: Created in 18:41 2020/7/28
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//獲取sqlSessionFactory物件
String resource = "com.Lv.resource/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//獲取sqlSessionFactory
public SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.4、實體類
2.5、Dao層介面
public interface UserDao {
List<User> getUser();
}
2.6、Dao層實現類由原來的UserDaoImpl變為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">
<mapper namespace="com.Lv.dao.UserDao">
<select id="getUser" resultType="com.Lv.User">
SELECT * FROM `user`
</select>
</mapper>
2.7、測試
注意點:每一個Mapper.xml檔案都需在核心配置檔案中配置
org.apache.ibatis.binding.BindingException: Type interface com.Lv.dao.UserDao is not known to the MapperRegistry.
Maven中資源生成或匯出失敗問題
java.lang.ExceptionInInitializerError
<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>
3、CRUD
1、namespace
namespace中的包要和Dao/Mapper的包名一致
2、select
選擇,查詢語句:
- id:就是對應namespace中的方法名;
- resultType:SQL語句的返回值
- parameterType:引數型別
編寫介面
//根據id查詢使用者
User getUser(int id);
在UserMapper.xml中配置
<select id="getUser" parameterType="int" resultType="com.Lv.pojo.User">
select * from user where id=#{id}
</select>
測試
@Test
public void userTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUser(2);
System.out.println(user);
sqlSession.close();
}
3、insert
<insert id="addUser" parameterType="com.Lv.pojo.User">
insert into user values (#{id},#{name},#{pwd})
</insert>
@Test
public void addUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.addUser(new User(4, "麗麗", "555555555"));
//增刪改需要提交事務
sqlSession.commit();
sqlSession.close();
}
4、update
<update id="updateUser" parameterType="com.Lv.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
5、delete
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
注意點:增刪改中需要提交事務
4、萬能的Map
假設,我們的實體類,或者資料庫中的表,欄位或者引數過多,我們應當考慮使用Map
//使用Map傳參增加加一個使用者
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="Map">
insert into user values (#{userid},#{username},#{userpwd})
</insert>
@Test
public void addUser2Test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("userid",5);
map.put("username","天天");
map.put("userpwd","123456");
int i = mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
Map傳遞引數,在SQL中取key即可
物件傳遞引數,直接在SQL中取物件的屬性即可
引數只有一個基本資料型別的情況下,可以直接在SQL中取到,即引數型別可以忽略不寫
多個引數用Map或者註解
4、配置解析
1、核心配置檔案
- mybatis-config.xml
- MyBatis的配置檔案包含了會深深影響MyBatis行為的設定和屬性資訊。
configuration(配置)
properties(屬性)
settings(設定)
typeAliases(類型別名)
typeHandlers(型別處理器)
objectFactory(物件工廠)
plugins(外掛)
environments(環境配置)
environment(環境變數)
transactionManager(事務管理器)
dataSource(資料來源)
databaseIdProvider(資料庫廠商標識)
mappers(對映器)
2、環境配置(environments)
- MyBatis 可以配置成適應多種環境
- 不過要記住:儘管可以配置多個環境,但每個 SqlSessionFactory例項只能選擇一種環境。
Mybatis預設的事務管理器是JDBC,連線池:POOLED
3、屬性(properties)
編寫一個配置檔案
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?character=UTF-8&useUnicode=true&useSSL=true
username=root
password=123456
在核心配置檔案中引入
注意:配置檔案中個標籤有順序,嚴格按照順序來
<?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">
<property name="username" value="aabb"/>
</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>
<!-- 每一個Mapper都需要在核心配置檔案中配置-->
<mappers>
<mapper resource="com/Lv/dao/UserMapper.xml"/>
</mappers>
</configuration>
- 可以直接使用外部引入檔案
- 可以在其中增加一些屬性配置
- 如果兩個檔案有同一個欄位,優先使用外部引入配置檔案的。
4、類型別名(typeAliases)
- 類型別名可為 Java 型別設定一個縮寫名字
- 意在降低冗餘的全限定類名書寫
第一種:
<!-- 為實體類取別名-->
<typeAliases>
<typeAlias type="com.Lv.pojo.User" alias="User"/>
</typeAliases><typeAlias type="com.Lv.pojo.User" alias="User"/>
第二種:
- 也可以指定一個包名,MyBatis 會在包名下面搜尋需要的 Java Bean
- 掃描實體類的包,它的預設別名就是實體類類名首字母小寫
<!-- 為實體類取別名-->
<typeAliases>
<package name="com.Lv.pojo"/>
</typeAliases>
在實體類比較少的時候,用第一種
在實體類比較多的時候用第二種
區別:第一種可以DIY(自定義)別名,第二種則不行。如果非要改,需要在實體類上加註解。
@Alias("user")
5、設定
這是 MyBatis 中極為重要的調整設定,它們會改變 MyBatis 的執行時行為
6、其他配置
7、對映器(mappers)
方式一:
使用相對於路徑的資源引用
<mappers>
<mapper resource="com/Lv/dao/UserMapper.xml"/>
</mappers>
方式二:
通過類名註冊
<mappers>
<mapper class="com.Lv.dao.UserMapper"/>
</mappers>
注意點:
- 介面和Mapper配置檔案必須同名
- 介面和Mapper配置檔案必須在同一個包下
方式三:
通過掃描包註冊
<mappers>
<package name="com.Lv.dao"/>
</mappers>
注意點:
- 介面和Mapper配置檔案必須同名
- 介面和Mapper配置檔案必須在同一個包下
8、生命週期和作用域
作用域和生命週期是至關重要的,因為錯誤的使用會導致非常嚴重的併發問題。
SqlSessionFactoryBuilder
一旦建立了 SqlSessionFactory,就不再需要它了,因此 SqlSessionFactoryBuilder 例項的最佳作用域是方法作用域(也就是區域性方法變數)
SqlSessionFactory
- 本質上和資料庫連線池一樣
- SqlSessionFactory 一旦被建立就應該在應用的執行期間一直存在,沒有任何理由丟棄它或重新建立另一個例項。
- SqlSessionFactory 的最佳作用域是應用作用域。
- 最簡單的就是使用單例模式或者靜態單例模式
SqlSession
- 每個執行緒都應該有它自己的 SqlSession 例項
- SqlSession的例項不是執行緒安全的,因此是不能被共享的,所以它的最佳的作用域是請求或方法作用域。
- 關閉操作很重要
這裡的每一個Mapper就代表一個具體的業務!
5、解決屬性名和欄位名不一致的問題
將不一致的屬性名和欄位名進行對映即可
<select id="getStudent" resultMap="stu">
select * from student
</select>
<resultMap id="stu" type="Student">
<result property="pwd" column="password"/>
</resultMap
6、日誌
1、日誌工廠
logImpl:STDOUT_LOGGING LOG4J
<!-- 設定日誌工廠-->
<settings>
<!-- 標準日誌工廠-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2、log4j
- Log4j是Apache的一個開源專案
- 可以控制日誌資訊輸送的目的地是控制檯、檔案、GUI元件
- 定義每一條日誌資訊的級別,我們能夠更加細緻地控制日誌的生成過程。
- 可以通過一個配置檔案來靈活地進行配置,而不需要修改應用的程式碼。
1、導包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、配置檔案
#newhappy log4j.properties start
log4j.rootLogger=DEBUG,myConsole,myLogFile
#控制檯輸出的相關設定
log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
log4j.appender.myConsole.layout.ConversionPattern=%5p [%t] (%F:%L) -%m%n
log4j.appender.myConsole.threshold=DEBUG
log4j.appender.myConsole.Target=System.out
#檔案輸出的相關設定
log4j.appender.myLogFile=org.apache.log4j.RollingFileAppender
log4j.appender.myLogFile.File=./log/Lv.log
log4j.appender.myLogFile.MaxFileSize=10mb
log4j.appender.myLogFile.MaxBackupIndex=2
log4j.appender.myLogFile.layout=org.apache.log4j.PatternLayout
log4j.appender.myLogFile.layout.ConversionPattern=%d{mmm d,yyyy hh:mm:ss a} : %p [%t] %m%n
log4j.appender.myLogFile.threshold=DEBUG
#日誌輸出級別
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
#newhappy log4j.properties end
3、配置日誌工廠為LOG4J
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
4、log4j的使用,執行剛才的測試
簡單使用
-
導包:import org.apache.log4j.Logger;
-
獲得log4j
static Logger logger = Logger.getLogger(UserMapperTest.class);
-
測試
@Test public void log4jTest(){ logger.info("info:進入log4jTest"); logger.debug("debug:進入log4jTest"); logger.error("error:進入log4jTest"); }
7、分頁
思考:為什麼要分頁?
- 減少資料的處理量
7.1、使用LImit分頁
語法:SELECT * FROM `user` LIMIT startidex,pagesize;
介面
List<User> getUsers(Map<String,Integer> map);
Mapper配置檔案
<select id="getUsers" parameterType="map" resultType="User">
SELECT * FROM `user` LIMIT #{startIndex},#{pageSize}
</select>
測試
@Test
public void getUsers(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("startIndex",1);
map.put("pageSize",3);
List<User> userList = mapper.getUsers(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
7.2、RowBounds分頁
7.3、分頁外掛
MyBatis分頁外掛PageHelper
8、註解開發
不需要在Mapper檔案中配置,直接可以在介面上用註解,不過只能用於簡單資料庫操作
示例:
//根據id查詢使用者
@Select("select * from user where id=#{id}")
User getUser(@Param("id") int id);
9、Lombok
使用
-
在IDEA中安裝Lombok外掛
-
匯入jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> <scope>provided</scope> </dependency>
-
在實體類上放註解
@Data @AllArgsConstructor @NoArgsConstructor
10、多對一處理
1、資料庫準備
CREATE TABLE `teacher`(
`id` INT(3) NOT NULL,
`name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `teacher` VALUES (1,'Lv老師')
CREATE TABLE `student`(
`id` INT(4) NOT NULL,
`name` VARCHAR(20),
`tid` INT(3),
PRIMARY KEY (`id`),
KEY `fktid`(`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` VALUES (1,'小明',1),(2,'小紅',1),(3,'小藍',1),(4,'小強',1),(5,'小黃',1)
2、測試環境搭建
- 新建實體類Teacher,Student
- 建立Mapper介面
- 建立Mapper.xml檔案
- 在核心配置檔案中繫結註冊我們的Mapper介面或檔案
- 測試查詢是否成功
3、按照查詢巢狀處理
<!-- 思路:
1、查詢所有學生資訊
2、根據獲取的tid查詢老師的資訊
-->
<select id="getStudentInfo" 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>
4、按照結果巢狀查詢
<!-- 根據結果巢狀查詢-->
<select id="getStudentInfo2" 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>
11、一對多
1、環境搭建
public class Teacher {
private Integer id;
private String name;
private List<Student> students;
public class Student {
private Integer id;
private String name;
private Integer tid;
2、按照結果巢狀查詢
<!--根據結果巢狀查詢-->
<select id="getTeacher" resultMap="TeacherStudent">
SELECT s.`id` sid,s.`name` sname,t.`id` tid,t.`name` tname FROM `student` s,`teacher` t
WHERE s.`tid`=t.`id`
</select>
<resultMap id="TeacherStudent" 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"/>
</collection>
</resultMap>
3、子查詢巢狀
<!--子查詢巢狀處理-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentBytid"/>
</resultMap>
<select id="getStudentBytid" resultType="Student">
select * from student where tid=#{tid}
</select>
小結:
- 關聯:association 【多對一】
- 結合:collection 【一對多】
- JavaType & ofType
- JavaType 用來指定實體類中屬性的型別
- ofType 用來指定對映到List或者集合中的pojo型別,泛型中的約束型別。
注意點:
- 保證SQL的可讀性,儘量保證通俗易懂
- 注意一對多和多對一中,屬性和欄位的問題
- 如果問題不好排查錯誤,可以使用日誌,建議使用Log4j
面試必問
- MySQL引擎
- InnoDB底層原理
- 索引
- 索引優化
12、動態SQL
什麼是動態SQL:動態SQL就是根據不同條件生成不同的SQL語句
1、環境搭建
資料庫建表
create table `blog` (
`id` varchar (150),
`title` varchar (150),
`author` varchar (150),
`create_time` datetime ,
`views` int (10)
);
編寫實體類
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
編寫實體類對應的Mapper
插入資料測試
//插入
int addBlog(Blog blog);
<insert id="addBlog" parameterType="blog">
INSERT INTO `blog`(`id`,`title`,`author`,`create_time`,`views`) VALUES
(#{id},#{title},#{author},#{createTime},#{views})
</insert>
@Test
public void insertBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(UUIDUntils.getId());
blog.setTitle("我在學Mybatis...");
blog.setAuthor("Lvvvvvvvvv");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(UUIDUntils.getId());
blog.setTitle("Mybatis 不太難的亞子");
mapper.addBlog(blog);
blog.setId(UUIDUntils.getId());
blog.setTitle("期待快學完框架");
mapper.addBlog(blog);
sqlSession.commit();
sqlSession.close();
}
注意:增刪改需要提交資料,增刪改需要提交資料,增刪改需要提交資料,重要的話講三遍
2、IF
<select id="queryBlog" resultType="Blog" parameterType="map">
select * from blog where 1=1
<if test="author != null">
and author=#{author}
</if>
</select>
3、choose(when,otherwise)、
<select id="queryBlog" resultType="Blog" parameterType="map">
select * from blog where
<choose>
<when test="title != null">
title=#{title}
</when>
<when test="author != null">
author=#{author}
</when>
<otherwise>
views=9999
</otherwise>
</choose>
</select>
4、trim(where,set)
“WHERE” 子句。而且,若子句的開頭為 “AND” 或 “OR”,where 元素也會將它們去除
SET 關鍵字,並會刪掉額外的逗號(這些逗號是在使用條件語句給列賦值時引入的)。
<select id="queryBlog" resultType="Blog" parameterType="map">
select * from blog
<where>
<if test="author != null">
and author=#{author}
</if>
<if test="title != null">
and title=#{title}
</if>
</where>
</select>
5、SQL片段
我們可以像提取公共類一樣,將公共SQL片段提取出來
<sql id="query-title-author">
<if test="author != null">
and author=#{author}
</if>
<if test="title != null">
and title=#{title}
</if>
</sql>
<select id="queryBlog" resultType="Blog" parameterType="map">
select * from blog
<where>
<include refid="query-title-author"></include>
</where>
</select>
6、ForEach
介面
//ForEach查詢
List<Blog> queryByForEach(Map map);
Mapper.xml
<select id="queryByForEach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
測試
@Test
public void queryByForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
Map map = new HashMap();
map.put("ids",ids);
List<Blog> blogs = mapper.queryByForEach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
13、快取
1、簡介
- 什麼是快取[Cache]?
- 存在記憶體中的臨時資料
- 將使用者經常查詢的資料放在快取(記憶體)中,使用者去查詢資料就不用從磁碟上(關係型資料庫資料檔案)查詢,從快取中查詢,從而提高查詢效率,解決了高併發系統的效能問題。
- 為什麼使用快取?
- 減少和資料庫的互動次數,較少系統開銷,提高系統效率。
- 什麼樣的資料能使用快取?
- 經常查詢並且不都經常改變的資料
2、Mybatis快取
- Mybatis包含一個非常強大的查詢快取特性,它可以非常方便地定製和配置快取。快取可以極大地提高查詢效率。
- Mybatis系統中預設定義了兩級快取:一級快取和二級快取
- 預設情況下,只有一級快取開啟。(SqkSession級別的快取,也稱為本地快取)
- 二級快取需要手動開啟和配置,他是基於namespace級別的快取。
- 為了提高擴充套件性,Mybatis定義了快取介面Cache。我們可以通過實現Cache介面來自定義二級快取
3、一級快取
- 一級快取也叫本地快取:
- 與資料庫同一次會話期間查詢的奧的資料會放在本地快取中
- 以後如果需要獲取相同的資料,直接從快取中吧,沒必要再去查詢資料庫。
測試步驟:
- 開啟日誌
- 測試在一個Session中查詢兩次相同的記錄
- 檢視日誌
快取失效的情況:
- 查詢不同的東西
- 增刪改操作,可能會改變原來的資料,所以必定會重新整理快取
- 查詢不同的Mapper.xml
- 手動清理換快取
小結:一級快取是預設開啟的,只在一次SqlSession中有效,也就是拿到連線到關閉連線這個區間。
一級快取相當於一個Map,用完即失。
4、二級快取
- 二級快取也叫全域性快取,一級快取作用域太低了,所以誕生了二級快取
- 基於naamespace級別的快取,一個名稱空間,對應一個二級快取
- 工作機制:
- 一個會話查詢一條資料,這個資料就會被放在當前會話的以及快取中
- 如果當前會話關閉了,這個會話對應的一級快取就沒了;但是我們想要的是,會話關閉了,以及快取中的資料被儲存到二級快取中;
- 新的會話查詢資訊,就可以從二級快取中獲取內容;
- 不同的Mapper查出的資料會放在自己對應的快取(map)中
步驟:
-
雖然全域性快取預設開啟,但還是在核心配置檔案中顯式開啟全域性快取
<!-- 開啟二級快取--> <setting name="cacheEnabled" value="true"/>
-
在需要的Mapper中開啟快取
-
測試
- 問題:我們需要將相應的實體類序列化,不然會報以下錯
java.io.NotSerializableException: com.Lv.pojo.Blog
實體類序列化
小結:
- 只要開啟了二級快取,在同一個Mapper中就有效
- 所有的資料都會暫時放到一級快取
- 只有當會話提交或關閉的時候,才會提交到二級快取