Mybatis-9.28
環(huán)境:
- JDK1.8
- Mysql 5.7
- maven 3.6.1
- IDEA
回顧:
- JDBC
- Mysql
- Java基礎(chǔ)
- Maven
- Junit
SSM框架:配置文件的。 最好的方式:看官網(wǎng)文檔;
1、簡(jiǎn)介
1.1、什么是Mybatis

- MyBatis 是一款優(yōu)秀的持久層框架
- 它支持定制化 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。
- MyBatis 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集。
- MyBatis 可以使用簡(jiǎn)單的 XML 或注解來(lái)配置和映射原生類(lèi)型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 對(duì)象)為數(shù)據(jù)庫(kù)中的記錄。
- MyBatis 本是apache的一個(gè)開(kāi)源項(xiàng)目iBatis, 2010年這個(gè)項(xiàng)目由apache software foundation 遷移到了google code,并且改名為MyBatis 。
- 2013年11月遷移到Github。
如何獲得Mybatis?
-
maven倉(cāng)庫(kù):
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
1.2、持久化
數(shù)據(jù)持久化
- 持久化就是將程序的數(shù)據(jù)在持久狀態(tài)和瞬時(shí)狀態(tài)轉(zhuǎn)化的過(guò)程
- 內(nèi)存:斷電即失
- 數(shù)據(jù)庫(kù)(Jdbc),io文件持久化。
- 生活:冷藏. 罐頭。
為什么需要需要持久化?
有一些對(duì)象,不能讓他丟掉。
內(nèi)存太貴了
1.3、持久層
Dao層,Service層,Controller層….
- 完成持久化工作的代碼塊
- 層界限十分明顯。
1.4 為什么需要Mybatis?
- 幫助程序猿將數(shù)據(jù)存入到數(shù)據(jù)庫(kù)中。
- 方便
- 傳統(tǒng)的JDBC代碼太復(fù)雜了。簡(jiǎn)化。框架。自動(dòng)化。
- 不用Mybatis也可以。更容易上手。 技術(shù)沒(méi)有高低之分
- 優(yōu)點(diǎn):
- 簡(jiǎn)單易學(xué)
- 靈活
- sql和代碼的分離,提高了可維護(hù)性。
- 提供映射標(biāo)簽,支持對(duì)象與數(shù)據(jù)庫(kù)的orm字段關(guān)系映射
- 提供對(duì)象關(guān)系映射標(biāo)簽,支持對(duì)象關(guān)系組建維護(hù)
- 提供xml標(biāo)簽,支持編寫(xiě)動(dòng)態(tài)sql。
最重要的一點(diǎn):使用的人多!
Spring SpringMVC SpringBoot
2、第一個(gè)Mybatis程序
思路:搭建環(huán)境-->導(dǎo)入Mybatis-->編寫(xiě)代碼-->測(cè)試!
2.1、搭建環(huán)境
搭建數(shù)據(jù)庫(kù)
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,'張三','123456'),
(3,'李四','123890')
新建項(xiàng)目
新建一個(gè)普通的maven項(xiàng)目
刪除src目錄
-
導(dǎo)入maven依賴(lài)
<!--導(dǎo)入依賴(lài)--> <dependencies> <!--mysql驅(qū)動(dòng)--> <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、創(chuàng)建一個(gè)模塊
-
編寫(xiě)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核心配置文件--> <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> -
編寫(xiě)mybatis工具類(lèi)
//sqlSessionFactory --> sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static{ try { //使用Mybatis第一步:獲取sqlSessionFactory對(duì)象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //既然有了 SqlSessionFactory,顧名思義,我們就可以從中獲得 SqlSession 的實(shí)例了。 // SqlSession 完全包含了面向數(shù)據(jù)庫(kù)執(zhí)行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
2.3、編寫(xiě)代碼
-
實(shí)體類(lèi)
package com.kuang.pojo; //實(shí)體類(lèi) 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接口
public interface UserDao { List<User> getUserList(); } -
接口實(shí)現(xiàn)類(lèi)由原來(lái)的UserDaoImpl轉(zhuǎn)變?yōu)橐粋€(gè) 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=綁定一個(gè)對(duì)應(yīng)的Dao/Mapper接口--> <mapper namespace="com.kuang.dao.UserDao"> <!--select查詢(xún)語(yǔ)句--> <select id="getUserList" resultType="com.kuang.pojo.User"> select * from mybatis.user </select> </mapper>
2.4、測(cè)試
注意點(diǎn):
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注冊(cè) mappers
-
junit測(cè)試
@Test public void test(){ //第一步:獲得SqlSession對(duì)象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //方式一:getMapper UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } //關(guān)閉SqlSession sqlSession.close(); }
你們可以能會(huì)遇到的問(wèn)題:
- 配置文件沒(méi)有注冊(cè)
- 綁定接口錯(cuò)誤。
- 方法名不對(duì)
- 返回類(lèi)型不對(duì)
- Maven導(dǎo)出資源問(wèn)題
3、CRUD
1、namespace
namespace中的包名要和 Dao/mapper 接口的包名一致!
2、select
選擇,查詢(xún)語(yǔ)句;
- id : 就是對(duì)應(yīng)的namespace中的方法名;
- resultType:Sql語(yǔ)句執(zhí)行的返回值!
- parameterType : 參數(shù)類(lèi)型!
-
編寫(xiě)接口
//根據(jù)ID查詢(xún)用戶(hù) User getUserById(int id); -
編寫(xiě)對(duì)應(yīng)的mapper中的sql語(yǔ)句
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User"> select * from mybatis.user where id = #{id} </select> -
測(cè)試
@Test public void getUserById() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
3、Insert
<!--對(duì)象中的屬性,可以直接取出來(lái)-->
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
4、update
<update id="updateUser" parameterType="com.kuang.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ;
</update>
5、Delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
注意點(diǎn):
- 增刪改需要提交事務(wù)!
6、分析錯(cuò)誤
- 標(biāo)簽不要匹配錯(cuò)
- resource 綁定mapper,需要使用路徑!
- 程序配置文件必須符合規(guī)范!
- NullPointerException,沒(méi)有注冊(cè)到資源!
- 輸出的xml文件中存在中文亂碼問(wèn)題!
- maven資源沒(méi)有導(dǎo)出問(wèn)題!
7、萬(wàn)能Map
假設(shè),我們的實(shí)體類(lèi),或者數(shù)據(jù)庫(kù)中的表,字段或者參數(shù)過(guò)多,我們應(yīng)當(dāng)考慮使用Map!
//萬(wàn)能的Map
int addUser2(Map<String,Object> map);
<!--對(duì)象中的屬性,可以直接取出來(lái) 傳遞map的key-->
<insert id="addUser" parameterType="map">
insert into mybatis.user (id, pwd) values (#{userid},#{passWord});
</insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid",5);
map.put("passWord","2222333");
mapper.addUser2(map);
sqlSession.close();
}
Map傳遞參數(shù),直接在sql中取出key即可! 【parameterType="map"】
對(duì)象傳遞參數(shù),直接在sql中取對(duì)象的屬性即可!【parameterType="Object"】
只有一個(gè)基本類(lèi)型參數(shù)的情況下,可以直接在sql中取到!
多個(gè)參數(shù)用Map,或者注解!
8、思考題
模糊查詢(xún)?cè)趺磳?xiě)?
-
Java代碼執(zhí)行的時(shí)候,傳遞通配符 % %
List<User> userList = mapper.getUserLike("%李%"); -
在sql拼接中使用通配符!
select * from mybatis.user where name like "%"#{value}"%"
4、配置解析
1、核心配置文件
mybatis-config.xml
-
MyBatis 的配置文件包含了會(huì)深深影響 MyBatis 行為的設(shè)置和屬性信息。
configuration(配置) properties(屬性) settings(設(shè)置) typeAliases(類(lèi)型別名) typeHandlers(類(lèi)型處理器) objectFactory(對(duì)象工廠(chǎng)) plugins(插件) environments(環(huán)境配置) environment(環(huán)境變量) transactionManager(事務(wù)管理器) dataSource(數(shù)據(jù)源) databaseIdProvider(數(shù)據(jù)庫(kù)廠(chǎng)商標(biāo)識(shí)) mappers(映射器)
2、環(huán)境配置(environments)
MyBatis 可以配置成適應(yīng)多種環(huán)境
不過(guò)要記?。罕M管可以配置多個(gè)環(huán)境,但每個(gè) SqlSessionFactory 實(shí)例只能選擇一種環(huán)境。
學(xué)會(huì)使用配置多套運(yùn)行環(huán)境!
Mybatis默認(rèn)的事務(wù)管理器就是 JDBC , 連接池 : POOLED
3、屬性(properties)
我們可以通過(guò)properties屬性來(lái)實(shí)現(xiàn)引用配置文件
這些屬性都是可外部配置且可動(dòng)態(tài)替換的,既可以在典型的 Java 屬性文件中配置,亦可通過(guò) properties 元素的子元素來(lái)傳遞?!綿b.properties】

編寫(xiě)一個(gè)配置文件
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">
<property name="username" value="root"/>
<property name="pwd" value="11111"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加一些屬性配置
- 如果兩個(gè)文件有同一個(gè)字段,優(yōu)先使用外部配置文件的!
4、類(lèi)型別名(typeAliases)
- 類(lèi)型別名是為 Java 類(lèi)型設(shè)置一個(gè)短的名字?!?/li>
- 存在的意義僅在于用來(lái)減少類(lèi)完全限定名的冗余。
<!--可以給實(shí)體類(lèi)起別名-->
<typeAliases>
<typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>
也可以指定一個(gè)包名,MyBatis 會(huì)在包名下面搜索需要的 Java Bean,比如:
掃描實(shí)體類(lèi)的包,它的默認(rèn)別名就為這個(gè)類(lèi)的 類(lèi)名,首字母小寫(xiě)!
<!--可以給實(shí)體類(lèi)起別名-->
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
在實(shí)體類(lèi)比較少的時(shí)候,使用第一種方式。
如果實(shí)體類(lèi)十分多,建議使用第二種。
第一種可以DIY別名,第二種則·不行·,如果非要改,需要在實(shí)體上增加注解
@Alias("user")
public class User {}
5、設(shè)置
這是 MyBatis 中極為重要的調(diào)整設(shè)置,它們會(huì)改變 MyBatis 的運(yùn)行時(shí)行為。


6、其他配置
- typeHandlers(類(lèi)型處理器)
- objectFactory(對(duì)象工廠(chǎng))
- plugins插件
- mybatis-generator-core
- mybatis-plus
- 通用mapper
7、映射器(mappers)
MapperRegistry:注冊(cè)綁定我們的Mapper文件;
方式一: 【推薦使用】
<!--每一個(gè)Mapper.XML都需要在Mybatis核心配置文件中注冊(cè)!-->
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件綁定注冊(cè)
<!--每一個(gè)Mapper.XML都需要在Mybatis核心配置文件中注冊(cè)!-->
<mappers>
<mapper class="com.kuang.dao.UserMapper"/>
</mappers>
注意點(diǎn):
- 接口和他的Mapper配置文件必須同名!
- 接口和他的Mapper配置文件必須在同一個(gè)包下!
方式三:使用掃描包進(jìn)行注入綁定
<!--每一個(gè)Mapper.XML都需要在Mybatis核心配置文件中注冊(cè)!-->
<mappers>
<package name="com.kuang.dao"/>
</mappers>
注意點(diǎn):
- 接口和他的Mapper配置文件必須同名!
- 接口和他的Mapper配置文件必須在同一個(gè)包下!
練習(xí)時(shí)間:
- 將數(shù)據(jù)庫(kù)配置文件外部引入
- 實(shí)體類(lèi)別名
- 保證UserMapper 接口 和 UserMapper .xml 改為一致!并且放在同一個(gè)包下!
8、生命周期和作用域

生命周期,和作用域,是至關(guān)重要的,因?yàn)殄e(cuò)誤的使用會(huì)導(dǎo)致非常嚴(yán)重的并發(fā)問(wèn)題。
SqlSessionFactoryBuilder:
- 一旦創(chuàng)建了 SqlSessionFactory,就不再需要它了
- 局部變量
SqlSessionFactory:
- 說(shuō)白了就是可以想象為 :數(shù)據(jù)庫(kù)連接池
- SqlSessionFactory 一旦被創(chuàng)建就應(yīng)該在應(yīng)用的運(yùn)行期間一直存在,沒(méi)有任何理由丟棄它或重新創(chuàng)建另一個(gè)實(shí)例。
- 因此 SqlSessionFactory 的最佳作用域是應(yīng)用作用域。
- 最簡(jiǎn)單的就是使用單例模式或者靜態(tài)單例模式。
SqlSession
- 連接到連接池的一個(gè)請(qǐng)求!
- SqlSession 的實(shí)例不是線(xiàn)程安全的,因此是不能被共享的,所以它的最佳的作用域是請(qǐng)求或方法作用域。
- 用完之后需要趕緊關(guān)閉,否則資源被占用!

這里面的每一個(gè)Mapper,就代表一個(gè)具體的業(yè)務(wù)!
5、解決屬性名和字段名不一致的問(wèn)題
1、 問(wèn)題
數(shù)據(jù)庫(kù)中的字段

新建一個(gè)項(xiàng)目,拷貝之前的,測(cè)試實(shí)體類(lèi)字段不一致的情況
public class User {
private int id;
private String name;
private String password;
}
測(cè)試出現(xiàn)問(wèn)題

// select * from mybatis.user where id = #{id}
//類(lèi)型處理器
// select id,name,pwd from mybatis.user where id = #{id}
解決方法:
-
起別名
<select id="getUserById" resultType="com.kuang.pojo.User"> select id,name,pwd as password from mybatis.user where id = #{id} </select>
2、resultMap
結(jié)果集映射
id name pwd
id name password
<!--結(jié)果集映射-->
<resultMap id="UserMap" type="User">
<!--column數(shù)據(jù)庫(kù)中的字段,property實(shí)體類(lèi)中的屬性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
-
resultMap元素是 MyBatis 中最重要最強(qiáng)大的元素 - ResultMap 的設(shè)計(jì)思想是,對(duì)于簡(jiǎn)單的語(yǔ)句根本不需要配置顯式的結(jié)果映射,而對(duì)于復(fù)雜一點(diǎn)的語(yǔ)句只需要描述它們的關(guān)系就行了。
-
ResultMap最優(yōu)秀的地方在于,雖然你已經(jīng)對(duì)它相當(dāng)了解了,但是根本就不需要顯式地用到他們。 - 如果世界總是這么簡(jiǎn)單就好了。
6、日志
6.1、日志工廠(chǎng)
如果一個(gè)數(shù)據(jù)庫(kù)操作,出現(xiàn)了異常,我們需要排錯(cuò)。日志就是最好的助手!
曾經(jīng):sout 、debug
現(xiàn)在:日志工廠(chǎng)!

SLF4J
LOG4J 【掌握】
LOG4J2
JDK_LOGGING
COMMONS_LOGGING
STDOUT_LOGGING 【掌握】
NO_LOGGING
在Mybatis中具體使用那個(gè)一日志實(shí)現(xiàn),在設(shè)置中設(shè)定!
STDOUT_LOGGING標(biāo)準(zhǔn)日志輸出
在mybatis核心配置文件中,配置我們的日志!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

6.2、Log4j
什么是Log4j?
- Log4j是Apache的一個(gè)開(kāi)源項(xiàng)目,通過(guò)使用Log4j,我們可以控制日志信息輸送的目的地是控制臺(tái)、文件、GUI組件
- 我們也可以控制每一條日志的輸出格式;
- 通過(guò)定義每一條日志信息的級(jí)別,我們能夠更加細(xì)致地控制日志的生成過(guò)程。
- 通過(guò)一個(gè)配置文件來(lái)靈活地進(jìn)行配置,而不需要修改應(yīng)用的代碼。
-
先導(dǎo)入log4j的包
<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> -
log4j.properties
#將等級(jí)為DEBUG的日志信息輸出到console和file這兩個(gè)目的地,console和file的定義在下面的代碼 log4j.rootLogger=DEBUG,console,file #控制臺(tái)輸出的相關(guān)設(shè)置 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 #文件輸出的相關(guān)設(shè)置 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 #日志輸出級(jí)別 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為日志的實(shí)現(xiàn)
<settings> <setting name="logImpl" value=""/> </settings> Log4j的使用!,直接測(cè)試運(yùn)行剛才的查詢(xún)

簡(jiǎn)單使用
在要使用Log4j 的類(lèi)中,導(dǎo)入包 import org.apache.log4j.Logger;
-
日志對(duì)象,參數(shù)為當(dāng)前類(lèi)的class
static Logger logger = Logger.getLogger(UserDaoTest.class); -
日志級(jí)別
logger.info("info:進(jìn)入了testLog4j"); logger.debug("debug:進(jìn)入了testLog4j"); logger.error("error:進(jìn)入了testLog4j");
7、分頁(yè)
思考:為什么要分頁(yè)?
- 減少數(shù)據(jù)的處理量
7.1、使用Limit分頁(yè)
語(yǔ)法:SELECT * from user limit startIndex,pageSize;
SELECT * from user limit 3; #[0,n]
使用Mybatis實(shí)現(xiàn)分頁(yè),核心SQL
-
接口
//分頁(yè) List<User> getUserByLimit(Map<String,Integer> map); -
Mapper.xml
<!--//分頁(yè)--> <select id="getUserByLimit" parameterType="map" resultMap="UserMap"> select * from mybatis.user limit #{startIndex},#{pageSize} </select> -
測(cè)試
@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex",1); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7.2、RowBounds分頁(yè)
不再使用SQL實(shí)現(xiàn)分頁(yè)
-
接口
//分頁(yè)2 List<User> getUserByRowBounds(); -
mapper.xml
<!--分頁(yè)2--> <select id="getUserByRowBounds" resultMap="UserMap"> select * from mybatis.user </select> -
測(cè)試
@Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //RowBounds實(shí)現(xiàn) RowBounds rowBounds = new RowBounds(1, 2); //通過(guò)Java代碼層面實(shí)現(xiàn)分頁(yè) List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7.3、分頁(yè)插件

了解即可,萬(wàn)一 以后公司的架構(gòu)師,說(shuō)要使用,你需要知道它是什么東西!
8、使用注解開(kāi)發(fā)
8.1、面向接口編程
- 大家之前都學(xué)過(guò)面向?qū)ο缶幊?,也學(xué)習(xí)過(guò)接口,但在真正的開(kāi)發(fā)中,很多時(shí)候我們會(huì)選擇面向接口編程
- 根本原因 : ==解耦== , 可拓展 , 提高復(fù)用 , 分層開(kāi)發(fā)中 , 上層不用管具體的實(shí)現(xiàn) , 大家都遵守共同的標(biāo)準(zhǔn) , 使得開(kāi)發(fā)變得容易 , 規(guī)范性更好
- 在一個(gè)面向?qū)ο蟮南到y(tǒng)中,系統(tǒng)的各種功能是由許許多多的不同對(duì)象協(xié)作完成的。在這種情況下,各個(gè)對(duì)象內(nèi)部是如何實(shí)現(xiàn)自己的,對(duì)系統(tǒng)設(shè)計(jì)人員來(lái)講就不那么重要了;
- 而各個(gè)對(duì)象之間的協(xié)作關(guān)系則成為系統(tǒng)設(shè)計(jì)的關(guān)鍵。小到不同類(lèi)之間的通信,大到各模塊之間的交互,在系統(tǒng)設(shè)計(jì)之初都是要著重考慮的,這也是系統(tǒng)設(shè)計(jì)的主要工作內(nèi)容。面向接口編程就是指按照這種思想來(lái)編程。
關(guān)于接口的理解
- 接口從更深層次的理解,應(yīng)是定義(規(guī)范,約束)與實(shí)現(xiàn)(名實(shí)分離的原則)的分離。
- 接口的本身反映了系統(tǒng)設(shè)計(jì)人員對(duì)系統(tǒng)的抽象理解。
- 接口應(yīng)有兩類(lèi):
- 第一類(lèi)是對(duì)一個(gè)個(gè)體的抽象,它可對(duì)應(yīng)為一個(gè)抽象體(abstract class);
- 第二類(lèi)是對(duì)一個(gè)個(gè)體某一方面的抽象,即形成一個(gè)抽象面(interface);
- 一個(gè)體有可能有多個(gè)抽象面。抽象體與抽象面是有區(qū)別的。
三個(gè)面向區(qū)別
- 面向?qū)ο笫侵?,我們考慮問(wèn)題時(shí),以對(duì)象為單位,考慮它的屬性及方法 .
- 面向過(guò)程是指,我們考慮問(wèn)題時(shí),以一個(gè)具體的流程(事務(wù)過(guò)程)為單位,考慮它的實(shí)現(xiàn) .
- 接口設(shè)計(jì)與非接口設(shè)計(jì)是針對(duì)復(fù)用技術(shù)而言的,與面向?qū)ο螅ㄟ^(guò)程)不是一個(gè)問(wèn)題.更多的體現(xiàn)就是對(duì)系統(tǒng)整體的架構(gòu)
8.2、使用注解開(kāi)發(fā)
-
注解在接口上實(shí)現(xiàn)
@Select("select * from user") List<User> getUsers(); -
需要再核心配置文件中綁定接口!
<!--綁定接口--> <mappers> <mapper class="com.kuang.dao.UserMapper"/> </mappers> 測(cè)試
本質(zhì):反射機(jī)制實(shí)現(xiàn)
底層:動(dòng)態(tài)代理!

Mybatis詳細(xì)的執(zhí)行流程!

8.3、CRUD
我們可以在工具類(lèi)創(chuàng)建的時(shí)候?qū)崿F(xiàn)自動(dòng)提交事務(wù)!
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
編寫(xiě)接口,增加注解
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
// 方法存在多個(gè)參數(shù),所有的參數(shù)前面必須加上 @Param("id")注解
@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 = #{uid}")
int deleteUser(@Param("uid") int id);
}
測(cè)試類(lèi)
【注意:我們必須要講接口注冊(cè)綁定到我們的核心配置文件中!】
關(guān)于@Param() 注解
- 基本類(lèi)型的參數(shù)或者String類(lèi)型,需要加上
- 引用類(lèi)型不需要加
- 如果只有一個(gè)基本類(lèi)型的話(huà),可以忽略,但是建議大家都加上!
- 我們?cè)赟QL中引用的就是我們這里的 @Param() 中設(shè)定的屬性名!
#{} ${} 區(qū)別
9、Lombok
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
- java library
- plugs
- build tools
- with one annotation your class
使用步驟:
在IDEA中安裝Lombok插件!
-
在項(xiàng)目中導(dǎo)入lombok的jar包
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> -
在實(shí)體類(lèi)上加注解即可!
@Data @AllArgsConstructor @NoArgsConstructor
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger
@Data
@Builder
@Singular
@Delegate
@Value
@Accessors
@Wither
@SneakyThrows
說(shuō)明:
@Data:無(wú)參構(gòu)造,get、set、tostring、hashcode,equals
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Getter
10、多對(duì)一處理
多對(duì)一:

- 多個(gè)學(xué)生,對(duì)應(yīng)一個(gè)老師
- 對(duì)于學(xué)生這邊而言, 關(guān)聯(lián) .. 多個(gè)學(xué)生,關(guān)聯(lián)一個(gè)老師 【多對(duì)一】
- 對(duì)于老師而言, 集合 , 一個(gè)老師,有很多學(xué)生 【一對(duì)多】

SQL:
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');
測(cè)試環(huán)境搭建
- 導(dǎo)入lombok
- 新建實(shí)體類(lèi) Teacher,Student
- 建立Mapper接口
- 建立Mapper.XML文件
- 在核心配置文件中綁定注冊(cè)我們的Mapper接口或者文件!【方式很多,隨心選】
- 測(cè)試查詢(xún)是否能夠成功!
按照查詢(xún)嵌套處理
<!--
思路:
1. 查詢(xún)所有的學(xué)生信息
2. 根據(jù)查詢(xún)出來(lái)的學(xué)生的tid,尋找對(duì)應(yīng)的老師! 子查詢(xún)
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--復(fù)雜的屬性,我們需要單獨(dú)處理 對(duì)象: association 集合: collection -->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
按照結(jié)果嵌套處理
<!--按照結(jié)果嵌套處理-->
<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 多對(duì)一查詢(xún)方式:
- 子查詢(xún)
- 聯(lián)表查詢(xún)
11、一對(duì)多處理
比如:一個(gè)老師擁有多個(gè)學(xué)生!
對(duì)于老師而言,就是一對(duì)多的關(guān)系!
環(huán)境搭建
- 環(huán)境搭建,和剛才一樣
實(shí)體類(lèi)
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
//一個(gè)老師擁有多個(gè)學(xué)生
private List<Student> students;
}
按照結(jié)果嵌套處理
<!--按結(jié)果嵌套查詢(xún)-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--復(fù)雜的屬性,我們需要單獨(dú)處理 對(duì)象: association 集合: collection
javaType="" 指定屬性的類(lèi)型!
集合中的泛型信息,我們使用ofType獲取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照查詢(xún)嵌套處理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" 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>
小結(jié)
- 關(guān)聯(lián) - association 【多對(duì)一】
- 集合 - collection 【一對(duì)多】
- javaType & ofType
- JavaType 用來(lái)指定實(shí)體類(lèi)中屬性的類(lèi)型
- ofType 用來(lái)指定映射到List或者集合中的 pojo類(lèi)型,泛型中的約束類(lèi)型!
注意點(diǎn):
- 保證SQL的可讀性,盡量保證通俗易懂
- 注意一對(duì)多和多對(duì)一中,屬性名和字段的問(wèn)題!
- 如果問(wèn)題不好排查錯(cuò)誤,可以使用日志 , 建議使用 Log4j
慢SQL 1s 1000s
面試高頻
- Mysql引擎
- InnoDB底層原理
- 索引
- 索引優(yōu)化!
12、動(dòng)態(tài) SQL
==什么是動(dòng)態(tài)SQL:動(dòng)態(tài)SQL就是指根據(jù)不同的條件生成不同的SQL語(yǔ)句==
利用動(dòng)態(tài) SQL 這一特性可以徹底擺脫這種痛苦。
動(dòng)態(tài) SQL 元素和 JSTL 或基于類(lèi)似 XML 的文本處理器相似。在 MyBatis 之前的版本中,有很多元素需要花時(shí)間了解。MyBatis 3 大大精簡(jiǎn)了元素種類(lèi),現(xiàn)在只需學(xué)習(xí)原來(lái)一半的元素便可。MyBatis 采用功能強(qiáng)大的基于 OGNL 的表達(dá)式來(lái)淘汰其它大部分元素。
if
choose (when, otherwise)
trim (where, set)
foreach
搭建環(huán)境
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT '博客標(biāo)題',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime NOT NULL COMMENT '創(chuàng)建時(shí)間',
`views` int(30) NOT NULL COMMENT '瀏覽量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
創(chuàng)建一個(gè)基礎(chǔ)工程
導(dǎo)包
編寫(xiě)配置文件
-
編寫(xiě)實(shí)體類(lèi)
@Data public class Blog { private int id; private String title; private String author; private Date createTime; private int views; } 編寫(xiě)實(shí)體類(lèi)對(duì)應(yīng)Mapper接口 和 Mapper.XML文件
IF
<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>
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)
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
<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>
==所謂的動(dòng)態(tài)SQL,本質(zhì)還是SQL語(yǔ)句 , 只是我們可以在SQL層面,去執(zhí)行一個(gè)邏輯代碼==
if
where , set , choose ,when
SQL片段
有的時(shí)候,我們可能會(huì)將一些功能的部分抽取出來(lái),方便復(fù)用!
-
使用SQL標(biāo)簽抽取公共的部分
<sql id="if-title-author"> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql> -
在需要使用的地方使用Include標(biāo)簽引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <include refid="if-title-author"></include> </where> </select>
注意事項(xiàng):
- 最好基于單表來(lái)定義SQL片段!
- 不要存在where標(biāo)簽
Foreach
select * from user where 1=1 and
<foreach item="id" collection="ids"
open="(" separator="or" close=")">
#{id}
</foreach>
(id=1 or id=2 or id=3)


<!--
select * from mybatis.blog where 1=1 and (id=1 or id = 2 or id=3)
我們現(xiàn)在傳遞一個(gè)萬(wàn)能的map , 這map中可以存在一個(gè)集合!
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
==動(dòng)態(tài)SQL就是在拼接SQL語(yǔ)句,我們只要保證SQL的正確性,按照SQL的格式,去排列組合就可以了==
建議:
- 現(xiàn)在Mysql中寫(xiě)出完整的SQL,再對(duì)應(yīng)的去修改成為我們的動(dòng)態(tài)SQL實(shí)現(xiàn)通用即可!
13、緩存 (了解)
13.1、簡(jiǎn)介
查詢(xún) : 連接數(shù)據(jù)庫(kù) ,耗資源!
一次查詢(xún)的結(jié)果,給他暫存在一個(gè)可以直接取到的地方!--> 內(nèi)存 : 緩存
我們?cè)俅尾樵?xún)相同數(shù)據(jù)的時(shí)候,直接走緩存,就不用走數(shù)據(jù)庫(kù)了
-
什么是緩存 [ Cache ]?
- 存在內(nèi)存中的臨時(shí)數(shù)據(jù)。
- 將用戶(hù)經(jīng)常查詢(xún)的數(shù)據(jù)放在緩存(內(nèi)存)中,用戶(hù)去查詢(xún)數(shù)據(jù)就不用從磁盤(pán)上(關(guān)系型數(shù)據(jù)庫(kù)數(shù)據(jù)文件)查詢(xún),從緩存中查詢(xún),從而提高查詢(xún)效率,解決了高并發(fā)系統(tǒng)的性能問(wèn)題。
-
為什么使用緩存?
- 減少和數(shù)據(jù)庫(kù)的交互次數(shù),減少系統(tǒng)開(kāi)銷(xiāo),提高系統(tǒng)效率。
-
什么樣的數(shù)據(jù)能使用緩存?
- 經(jīng)常查詢(xún)并且不經(jīng)常改變的數(shù)據(jù)?!究梢允褂镁彺妗?/li>
13.2、Mybatis緩存
- MyBatis包含一個(gè)非常強(qiáng)大的查詢(xún)緩存特性,它可以非常方便地定制和配置緩存。緩存可以極大的提升查詢(xún)效率。
- MyBatis系統(tǒng)中默認(rèn)定義了兩級(jí)緩存:一級(jí)緩存和二級(jí)緩存
默認(rèn)情況下,只有一級(jí)緩存開(kāi)啟。(SqlSession級(jí)別的緩存,也稱(chēng)為本地緩存)
二級(jí)緩存需要手動(dòng)開(kāi)啟和配置,他是基于namespace級(jí)別的緩存。
為了提高擴(kuò)展性,MyBatis定義了緩存接口Cache。我們可以通過(guò)實(shí)現(xiàn)Cache接口來(lái)自定義二級(jí)緩存
13.3、一級(jí)緩存
- 一級(jí)緩存也叫本地緩存: SqlSession
- 與數(shù)據(jù)庫(kù)同一次會(huì)話(huà)期間查詢(xún)到的數(shù)據(jù)會(huì)放在本地緩存中。
- 以后如果需要獲取相同的數(shù)據(jù),直接從緩存中拿,沒(méi)必須再去查詢(xún)數(shù)據(jù)庫(kù);
測(cè)試步驟:
- 開(kāi)啟日志!
- 測(cè)試在一個(gè)Sesion中查詢(xún)兩次相同記錄
- 查看日志輸出

緩存失效的情況:
查詢(xún)不同的東西
增刪改操作,可能會(huì)改變?cè)瓉?lái)的數(shù)據(jù),所以必定會(huì)刷新緩存!

查詢(xún)不同的Mapper.xml
手動(dòng)清理緩存!

小結(jié):一級(jí)緩存默認(rèn)是開(kāi)啟的,只在一次SqlSession中有效,也就是拿到連接到關(guān)閉連接這個(gè)區(qū)間段!
一級(jí)緩存就是一個(gè)Map。
13.4、二級(jí)緩存
- 二級(jí)緩存也叫全局緩存,一級(jí)緩存作用域太低了,所以誕生了二級(jí)緩存
- 基于namespace級(jí)別的緩存,一個(gè)名稱(chēng)空間,對(duì)應(yīng)一個(gè)二級(jí)緩存;
- 工作機(jī)制
- 一個(gè)會(huì)話(huà)查詢(xún)一條數(shù)據(jù),這個(gè)數(shù)據(jù)就會(huì)被放在當(dāng)前會(huì)話(huà)的一級(jí)緩存中;
- 如果當(dāng)前會(huì)話(huà)關(guān)閉了,這個(gè)會(huì)話(huà)對(duì)應(yīng)的一級(jí)緩存就沒(méi)了;但是我們想要的是,會(huì)話(huà)關(guān)閉了,一級(jí)緩存中的數(shù)據(jù)被保存到二級(jí)緩存中;
- 新的會(huì)話(huà)查詢(xún)信息,就可以從二級(jí)緩存中獲取內(nèi)容;
- 不同的mapper查出的數(shù)據(jù)會(huì)放在自己對(duì)應(yīng)的緩存(map)中;
步驟:
-
開(kāi)啟全局緩存
<!--顯示的開(kāi)啟全局緩存--> <setting name="cacheEnabled" value="true"/> -
在要使用二級(jí)緩存的Mapper中開(kāi)啟
<!--在當(dāng)前Mapper.xml中使用二級(jí)緩存--> <cache/>也可以自定義參數(shù)
<!--在當(dāng)前Mapper.xml中使用二級(jí)緩存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> -
測(cè)試
-
問(wèn)題:我們需要將實(shí)體類(lèi)序列化!否則就會(huì)報(bào)錯(cuò)!
Caused by: java.io.NotSerializableException: com.kuang.pojo.User
-
小結(jié):
- 只要開(kāi)啟了二級(jí)緩存,在同一個(gè)Mapper下就有效
- 所有的數(shù)據(jù)都會(huì)先放在一級(jí)緩存中;
- 只有當(dāng)會(huì)話(huà)提交,或者關(guān)閉的時(shí)候,才會(huì)提交到二級(jí)緩沖中!
13.5、緩存原理

13.6、自定義緩存-ehcache
Ehcache是一種廣泛使用的開(kāi)源Java分布式緩存。主要面向通用緩存
要在程序中使用ehcache,先要導(dǎo)包!
<!-- 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緩存實(shí)現(xiàn)!
<!--在當(dāng)前Mapper.xml中使用二級(jí)緩存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
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分為內(nèi)存和磁盤(pán)兩級(jí),此屬性定義磁盤(pán)的緩存位置。參數(shù)解釋如下:
user.home – 用戶(hù)主目錄
user.dir – 用戶(hù)當(dāng)前工作目錄
java.io.tmpdir – 默認(rèn)臨時(shí)文件路徑
-->
<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:默認(rèn)緩存策略,當(dāng)ehcache找不到定義的緩存時(shí),則使用這個(gè)緩存策略。只能定義一個(gè)。
-->
<!--
name:緩存名稱(chēng)。
maxElementsInMemory:緩存最大數(shù)目
maxElementsOnDisk:硬盤(pán)最大緩存?zhèn)€數(shù)。
eternal:對(duì)象是否永久有效,一但設(shè)置了,timeout將不起作用。
overflowToDisk:是否保存到磁盤(pán),當(dāng)系統(tǒng)當(dāng)機(jī)時(shí)
timeToIdleSeconds:設(shè)置對(duì)象在失效前的允許閑置時(shí)間(單位:秒)。僅當(dāng)eternal=false對(duì)象不是永久有效時(shí)使用,可選屬性,默認(rèn)值是0,也就是可閑置時(shí)間無(wú)窮大。
timeToLiveSeconds:設(shè)置對(duì)象在失效前允許存活時(shí)間(單位:秒)。最大時(shí)間介于創(chuàng)建時(shí)間和失效時(shí)間之間。僅當(dāng)eternal=false對(duì)象不是永久有效時(shí)使用,默認(rèn)是0.,也就是對(duì)象存活時(shí)間無(wú)窮大。
diskPersistent:是否緩存虛擬機(jī)重啟期數(shù)據(jù) Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:這個(gè)參數(shù)設(shè)置DiskStore(磁盤(pán)緩存)的緩存區(qū)大小。默認(rèn)是30MB。每個(gè)Cache都應(yīng)該有自己的一個(gè)緩沖區(qū)。
diskExpiryThreadIntervalSeconds:磁盤(pán)失效線(xiàn)程運(yùn)行時(shí)間間隔,默認(rèn)是120秒。
memoryStoreEvictionPolicy:當(dāng)達(dá)到maxElementsInMemory限制時(shí),Ehcache將會(huì)根據(jù)指定的策略去清理內(nèi)存。默認(rèn)策略是LRU(最近最少使用)。你可以設(shè)置為FIFO(先進(jìn)先出)或是LFU(較少使用)。
clearOnFlush:內(nèi)存數(shù)量最大時(shí)是否清除。
memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認(rèn)策略)、FIFO(先進(jìn)先出)、LFU(最少訪(fǎng)問(wèn)次數(shù))。
FIFO,first in first out,這個(gè)是大家最熟的,先進(jìn)先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點(diǎn)就是講一直以來(lái)最少被使用的。如上面所講,緩存的元素有一個(gè)hit屬性,hit值最小的將會(huì)被清出緩存。
LRU,Least Recently Used,最近最少使用的,緩存的元素有一個(gè)時(shí)間戳,當(dāng)緩存容量滿(mǎn)了,而又需要騰出地方來(lái)緩存新的元素的時(shí)候,那么現(xiàn)有緩存元素中時(shí)間戳離當(dāng)前時(shí)間最遠(yuǎn)的元素將被清出緩存。
-->
</ehcache>
Redis數(shù)據(jù)庫(kù)來(lái)做緩存! K-V