【SSM框架】MyBatis
MyBatis
- 1、簡介
- 1.1、什么是MyBatis
- 1.2、持久化
- 1.3、持久層
- 1.4、為什么需要MyBatis
- 2、第一個MyBatis程序
- 2.1、搭建環境
- 2.2、創建一個模塊
- 2.3、編寫代碼
- 2.4、測試
- 3、CRUD
- 1、namespace
- 2、編寫接口
- 3、編寫接口對應的mapper中的語句
- 4、測試
- 5、注意點
- 6、萬能map
- 7、模糊查詢
- 4、配置解析
- 1、核心配置文件
- 2、環境配置(environments)
- 3、屬性(properties)
- 4、類型別名(typeAliases)
- 5、設置(settings)
- 6、其他配置
- 7、映射器(mappers)
- 8、生命周期和作用域
- SqlSessionFactoryBuilder
- SqlSessionFactory
- SqlSession
- 5、解決屬性名和字段名不一致的問題
- 1、問題
- 2、resultMap
- 6、日志
- 6.1、日志工廠
- 6.2、Log4J
- 7、分頁
- 7.1、使用limit分頁
- 7.2、RowBounds分頁
- 7.3、分頁插件
- 8、使用注解開發
- 8.1、面向接口編程
- 8.2、使用注解開發
- 8.3、CRUD
- 9、Lombok
- 10、多對一處理
- 測試環境搭建
- 按照查詢嵌套處理
- 按照結果嵌套處理
- 11、一對多處理
- 環境搭建
- 按照結果嵌套處理
- 按照查詢嵌套處理
- 小結
- 注意點
- 12、動態SQL
- 搭建環境
- if
- choose (when, otherwise)
- trim (where, set)
- SQL片段
- foreach
- 13、緩存
- 13.1、簡介
- 13.2、mybatis緩存
- 13.3、一級緩存
- 13.4、二級緩存
- 13.5、緩存原理
- 13.6、自定義緩存-ehcache
SMM框架 好的學習方式:看官方文檔
1、簡介
1.1、什么是MyBatis
- MyBatis 是一款優秀的持久層框架
- 它支持自定義 SQL、存儲過程以及高級映射。
- MyBatis 免除了幾乎所有的 JDBC 代碼以及設置參數和獲取結果集的工作。
- MyBatis 可以通過簡單的 XML 或注解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)為數據庫中的記錄。
- MyBatis本是apache的一個開源項目iBatis,2010年這個項目且改名為MyBatis。
- 2013年11月遷移到Github。
如何獲得Mybatis
-
maven倉庫
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</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層 server層 controller層
- 完成持久化工作的代碼塊
- 層界限十分明顯
1.4、為什么需要MyBatis
- 幫忙程序員將數據存入到數據庫中
- 傳統的jdbc太復雜了。簡化。框架。自動化。
- 優點:
- 簡單易學
- 靈活
- 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,'zyy','123456'), (2,'張三','123456'), (3,'李四','123456');新建項目
新建一個普通的maven項目
刪除src目錄(作為父工程)
導入maven依賴
<!-- 導入依賴 --><dependencies><!-- MySQL --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><!-- MyBatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency><!-- juint --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>2.2、創建一個模塊
-
編寫mybatis的核心配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration 核心配置文件--> <configuration><!-- environment 元素體中包含了事務管理和連接池的配置--><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${com.mysql.cj.jdbc.Driver}"/><property name="url" value="${jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8}"/><property name="username" value="${root}"/><property name="password" value="${123456}"/></dataSource></environment></environments><!-- mappers 元素則包含了一組映射器(mapper),這些映射器的 XML 映射文件包含了 SQL 代碼和映射定義信息。--><!-- 每一個Mapper.xml都需要在mybatis核心配置文件中注冊 --></configuration> -
編寫mybatis工具類
package com.sue.utils;import org.apache.ibatis.io.Resources; import org.apache.ibatis.jdbc.SQL; 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;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.utils* @ClassName : .java* @createTime : 2022/9/7 15:20* @Email : 1420779618@qq.com* @公眾號 :* @Website :* @Description :*/ //工具類SqlSessionFactory-->SqlSession public class MybatisUtil {private static SqlSessionFactory sqlSessionFactory;static {String resource = "mybatis-config.xml";try {//使用Mybatis第一步:獲取SqlSessionFactory對象InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {throw new RuntimeException(e);}}// 既然有了 SqlSessionFactory,顧名思義,我們可以從中獲得 SqlSession 的實例。// SqlSession 提供了在數據庫執行 org.apache.ibatis.jdbc.SQL 命令所需的所有方法。public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();} }
2.3、編寫代碼
-
實體類
package com.sue.pojo;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.pojo* @ClassName : .java* @createTime : 2022/9/7 15:29* @Email : 1420779618@qq.com* @公眾號 :* @Website :* @Description :*/ 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;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", p wd='" + pwd + '\'' +'}';} } -
Dao接口
package com.sue.dao;import com.sue.pojo.User;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:31* @Email : 1420779618@qq.com* @公眾號 :* @Website :* @Description :*/ public interface UserDao {List<User> getUserList(); } -
接口實現類(由原來的UserDaoImpl轉為一個Mapper配置文件)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace=綁定一個對應的DAO/Mapper接口--> <mapper namespace="com.sue.dao.UserDao"><!-- id就是方法的名字 --><select id="getUserList" resultType="com.sue.pojo.User">select *from mybatis.user;</select></mapper>
2.4、測試
注意點:
org.apache.ibatis.binding.BindingException: Type interface com.sue.dao.UserDao is not known to the MapperRegistry.
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-WnNA5Wf1-1662864948627)(C:\Users\Genius Sue\AppData\Roaming\Typora\typora-user-images\image-20220907155016783.png)]
Caused by: java.io.IOException: Could not find resource com/zyy/dao/UserMapper.xml
pom改成:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!-- 父工程 --><groupId>com.sue</groupId><artifactId>Mybatis-Study</artifactId><packaging>pom</packaging><version>1.0-SNAPSHOT</version><modules><module>mybatis-01</module></modules><!-- 導入依賴 --><dependencies><!-- MySQL --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><!-- MyBatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency><!-- juint --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><!--在build中配置resources,來防止我們資源導出失敗的問題--><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></project>核心配置文件中注冊mappers
-
junit測試
package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:45* @Email : 1420779618@qq.com* @公眾號 :* @Website :* @Description :*/ public class UserDaoTest { // 最好將映射器放在方法作用域內@Testpublic void test(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserDao mapper = sqlSession.getMapper(UserDao.class);List<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}}finally {sqlSession.close();}// //獲得 SqlSession 對象 // SqlSession sqlSession = MybatisUtil.getSqlSession(); // // //執行SQL // UserDao mapper = sqlSession.getMapper(UserDao.class); // List<User> userList = mapper.getUserList(); // // for (User user : userList) { // System.out.println(user); // } // // //關閉SqlSession // sqlSession.close();} }
3、CRUD
1、namespace
namespace中的包名要和dao/mapper接口的包名一致
選擇,查詢語句:
- id :就是對應的namespace中的方法名字
- resultType:sql語句執行的返回值類型
- parameterType:參數類型
2、編寫接口
package com.sue.dao;import com.sue.pojo.User;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:31* @Email : 1420779618@qq.com* @公眾號 :* @Website :* @Description :*/ public interface UserMapper {//查詢所有用戶List<User> getUserList();//根據ID查詢用戶User getUserById(int id);//插入一個用戶int addUser(User user);//修改用戶int updateUser(User user);//刪除一個用戶int deleteUser(int id);}3、編寫接口對應的mapper中的語句
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace=綁定一個對應的DAO/Mapper接口--> <mapper namespace="com.sue.dao.UserMapper"><!-- id就是方法的名字 --><select id="getUserList" resultType="com.sue.pojo.User">select *from mybatis.user;</select><select id="getUserById" parameterType="int" resultType="com.sue.pojo.User">select *from mybatis.userwhere id=#{id};</select><!-- 對象中的屬性可以直接取出來 --><insert id="addUser" parameterType="com.sue.pojo.User">insert into mybatis.user (id,name,pwd) values(#{id},#{name},#{pwd})</insert><update id="updateUser" parameterType="com.sue.pojo.User">update mybatis.userset name = #{name},pwd=#{pwd}where id = #{id};</update><delete id="deleteUser" parameterType="int">delete from mybatis.userwhere id = #{id};</delete></mapper>4、測試
package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:45* @Email : 1420779618@qq.com* @公眾號 :* @Website :* @Description :*/ public class UserMapperTest {@Testpublic void test(){//獲得 SqlSession 對象SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);//執行SQLList<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}}finally {//關閉SqlSessionsqlSession.close();}}@Testpublic void getUserById(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);User userById = mapper.getUserById(2);System.out.println(userById);}finally {sqlSession.close();}}//增刪改需要提交事物@Testpublic void addUser(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.addUser(new User(5,"Genius Sue","123456"));System.out.println("插入成功");//提交事物sqlSession.commit();}finally {sqlSession.close();}}@Testpublic void updateUser(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.updateUser(new User(4,"Genius","123456"));//提交事物sqlSession.commit();System.out.println("更新成功");}finally {sqlSession.close();}}@Testpublic void deleteUser(){SqlSession sqlSession = null;try {sqlSession = MybatisUtil.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.deleteUser(5);//提交事物sqlSession.commit();System.out.println("刪除成功");}finally {if (sqlSession!=null){sqlSession.close();}}}}5、注意點
-
增刪改需要提交事務才會生效
-
標簽不要匹配錯!
-
resource綁定mapper,需要使用路徑 .
-
程序配置文件必須符合規范!
-
NullPointerException,沒有注冊到資源
-
輸出的xml文件中存在中文亂碼問題,更改編碼UTF-8
-
maven資源沒有導出問題
6、萬能map
假設,我們的實例類,或者數據庫中的表,字段或者參數過多,我們應該考慮使用map
接口
int addUser2(Map<String, Object> map);mapper
<insert id="addUser2" parameterType="map">insert into `user`(id, name, pwd) values (#{userId},#{userName},#{password}) </insert>測試
@Testpublic void addUser2() {SqlSession sqlSession = null;try {Map<String, Object> map = new HashMap<>();map.put("userId", 5);map.put("userName", "GCD");map.put("password", "123456");sqlSession = MybatisUtils.getSqlSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);int num = userMapper.addUser2(map);if (num > 0) {System.out.println("插入成功!");}sqlSession.commit();} finally {if (sqlSession != null) {sqlSession.close();}}}Map傳遞參數,直接在sql中取出key即可!
對象傳遞參數,直接在sql中取對象的屬性即可!
只有一個基本類型的情況下,可以直接在sql中取到!
多個參數用Map,或者注解!
7、模糊查詢
java代碼執行的時候,傳遞通配符%
List<User> userList = userMapper.getUserLike("%李%");在sql中拼接使用通配符 (不推薦,容易引起sql注入問題)
<!-- select id, name, pwd from `user` where id = ? --><!-- select id, name, pwd from `user` where id = 1 一般情況--><!-- select id, name, pwd from `user` where id = 1 or 1=1 sql注入情況--><select id="getUserLike" resultType="com.zyy.pojo.User" parameterType="string">select id, name, pwd from `user` where name like "%"#{value}"%"</select>4、配置解析
1、核心配置文件
-
mybatis-config.xml
-
MyBatis 的配置文件包含了會深深影響 MyBatis 行為的設置和屬性信息。 配置文檔的頂層結構如下:
-
configuration(配置)
- [properties(屬性)]
- [settings(設置)]
- [typeAliases(類型別名)]
- [typeHandlers(類型處理器)]
- [objectFactory(對象工廠)]
- [plugins(插件)]
- environments(環境配置)
- environment(環境變量)
- transactionManager(事務管理器)
- dataSource(數據源)
- environment(環境變量)
- [databaseIdProvider(數據庫廠商標識)]
- [mappers(映射器)]
2、環境配置(environments)
MyBatis 可以配置成適應多種環境
不過要記住:盡管可以配置多個環境,但每個 SqlSessionFactory 實例只能選擇一種環境。
學會使用配置多套運行環境!
事務管理器(transactionManager)
在 MyBatis 中有兩種類型的事務管理器(也就是 type=“[JDBC|MANAGED]”):
數據源(dataSource)
有三種內建的數據源類型(也就是 type=“[UNPOOLED|POOLED|JNDI]”):
MyBatis默認的事務管理器就是JDBC,連接池:POOLED
3、屬性(properties)
我們可以通過properties屬性來實現引用配置文件
這些屬性可以在外部進行配置,并可以進行動態替換。你既可以在典型的 Java 屬性文件中配置這些屬性,也可以在 properties 元素的子元素中設置。【db.properties】
在xml中,所有的標簽都可以規定其順序
編寫一個配置文件
db.properties
driver = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8 username = root password =123456在核心配置文件中引入
<properties resource="db.properties"><property name="username" value="root"/><property name="password" value="123456"/></properties>- 可以直接引入外部文件
- 可以在其中增加一些屬性配置
- 如果兩個文件有同一個字段,優先使用外部配置文件的!
4、類型別名(typeAliases)
- 類型別名可為 Java 類型設置一個縮寫名字。
- 意在降低冗余的全限定類名書寫。
也可以指定一個包名,MyBatis 會在包名下面搜索需要的 Java Bean
掃描實體類的包,它的默認別名就是這個類的類名,首字母小寫。
<!-- 可以給實體類取別名 --> <typeAliases><package name="com.sue.pojo"/> </typeAliases>在實體類比較少的時候,使用第一種方式。
如果實體類比較多,建議使用第二種。
第一種可以自定義別名,第二種不行,如果非要改的話,需要在實體上增加注解
@Alias("user") public class User {}5、設置(settings)
這是 MyBatis 中極為重要的調整設置,它們會改變 MyBatis 的運行時行為。
6、其他配置
- typeHandlers(類型處理器)
- objectFactory(對象工廠)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
7、映射器(mappers)
MapperRegistry:注冊綁定我們的mapper文件
方式一:
<!-- 每一個Mapper.xml都需要在mybatis核心配置文件中注冊 --> <mappers><mapper resource="com/sue/dao/UserMapper.xml"/> </mappers>方式二:使用class文件綁定注冊
<mappers><mapper class="com.sue.dao.UserMapper"/> </mappers>注意點:
- 接口和它的Mapper配置文件必須同名!
- 接口和它的Mapper配置文件必須在同一個包下!
方式三:使用掃描包進行注入綁定
<mappers><package name="com.sue.dao"/> </mappers>注意點:
- 接口和它的Mapper配置文件必須同名!
- 接口和它的Mapper配置文件必須在同一個包下!
8、生命周期和作用域
生命周期和作用域類別是至關重要的,因為錯誤的使用會導致非常嚴重的并發問題。
SqlSessionFactoryBuilder
- 一旦創建了 SqlSessionFactory,就不再需要它了
- 局部變量
SqlSessionFactory
- 說白了就是可以想象為:數據庫連接池
- 一旦被創建就應該在應用的運行期間一直存在,沒有任何理由丟棄它或重新創建另一個實例。
- SqlSessionFactory 的最佳作用域是應用作用域
- 最簡單的就是使用單例模式或者靜態單例模式。
SqlSession
-
連接到連接池的一個請求
-
每個線程都應該有它自己的 SqlSession 實例。SqlSession 的實例不是線程安全的,因此是不能被共享的,所以它的最佳的作用域是請求或方法作用域。
-
用完之后需要趕緊關閉,否則資源被占用!
@Test public void addUser(){SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.insertUser(new User(8,"GCD","123456"));sqlSession.commit();}finally {if (sqlSession!=null){sqlSession.close();}}}
這里的每一個mapper,就代表一個具體的業務!
5、解決屬性名和字段名不一致的問題
1、問題
新建一個項目,拷貝之前的,測試實體類字段不一致的情況
*/ public class User {private int id;private String name;private String password;...... }解決方法:
-
起別名
<select id="getUserById" resultType="User">select id, name, pwd as `password`from mybatis.userwhere id = #{id}; </select>
2、resultMap
結果集映射
id name pwd id name passwod <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.sue.dao.UserMapper"><insert id="insertUser" parameterType="User">insert into mybatis.user (id,name,pwd)values (#{id},#{name},#{pwd});</insert><resultMap id="userMap" type="User"><!-- column數據庫列名-字段 property實體類中的屬性名 --><result column="id" property="id"/><result column="name" property="name"/><result column="pwd" property="password"/></resultMap><select id="getUserById" resultMap="userMap">select *from mybatis.userwhere id = #{id}</select></mapper>- resultMap 元素是 MyBatis 中最重要最強大的元素
- ResultMap 的設計思想是,對簡單的語句做到零配置,對于復雜一點的語句,只需要描述語句之間的關系就行了。
- ResultMap 的優秀之處——你完全可以不用顯式地配置它們。
如果這個世界總是這么簡單就好了。
6、日志
6.1、日志工廠
如果一個數據庫操作 出現了異常,我們需要排錯,日志就是最好的助手
曾經:sout、debug
現在:日志工廠
- SLF4J
- LOG4J(deprecated since 3.5.9)
- 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=%d %p [%c] - %m%n#文件輸出的相關配置 log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/zyy.log log4j.appender.file.MaxFileSize=10MB log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d %p [%c] - %m%n#日志輸出級別 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG配置log4j為mybatis日志的實現
<settings><setting name="logImpl" value="LOG4J"/> </settings>使用log4j,運行測試
簡單使用
在要使用log4j的類中,導入包import org.apache.log4j.Logger;
日志對象,參數為當前類的class
static Logger logger = Logger.getLogger(UserDaoTest.class);日志級別
@Test public void testLog4j(){logger.info("info:進入了testLog4j");logger.debug("debug:進入了testLog4j");logger.error("error:進入了testLog4j"); }7、分頁
- 減少數據的處理量
7.1、使用limit分頁
-- 語法 select * from `user` limit startIndex,pageSize; select * from `user` limit 2; -- 相當于 select * from `user` limit 0,2;使用mybatis實現分頁,核心sql
接口
/** * 分頁查詢 * @param map * @return */ List<User> getUserByLimit(Map<String, Integer> map);Mapper.xml
<select id="getUserByLimit" parameterType="map" resultMap="userMap">select id, name, pwd from `user` limit #{startIndex},#{pageSize} </select>測試
@Test public void getUserByLimit() {SqlSession sqlSession = null;try {sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);Map<String, Integer> map = new HashMap<>(16);map.put("startIndex", 0);map.put("pageSize", 2);List<User> userList = mapper.getUserByLimit(map);for (User user : userList) {logger.info(user);}} finally {if (sqlSession != null) {sqlSession.close();}}}7.2、RowBounds分頁
不再使用sql實現分頁
接口
/*** 分頁查詢* @return*/ List<User> getUserByRowBounds();Mapper.xml
<select id="getUserByRowBounds" resultMap="userMap">select id, name, pwd from `user` </select>測試
@Test public void getUserByRowBounds() {SqlSession sqlSession = null;try {sqlSession = MybatisUtils.getSqlSession();RowBounds rowBounds = new RowBounds(1,2);List<User> userList = sqlSession.selectList("com.sue.dao.UserMapper.getUserByRowBounds",null, rowBounds);for (User user : userList) {logger.info(user);}} finally {if (sqlSession != null) {sqlSession.close();}}}7.3、分頁插件
官方文檔:https://pagehelper.github.io/
8、使用注解開發
8.1、面向接口編程
- 根本原因:解耦,可拓展,提高復用,分層開發中,上層不用管具體的實現,大家都遵守共同的標準,使得開發變得容易,規范性更好。
- 在一個面向對象的系統中,系統的各種功能是由許許多多的不同對象協作完成的。在這種情況下,各個對象內部是如何實現自己的,對系統設計人員來講就不用那么重要了;
- 而各個對象之前的協作關系則成為系統設計的關鍵。小到不同類之前的通訊,大到各模塊之間的交互,在系統設計之初都是要著重要考慮的,這也是系統設計的主要工作內容。面向接口編程就是指按照這種思想來編程。
關于接口的理解
- 接口從更深層次的理解,應是定義(規范,約束)與實現(名實分離的原則)的分離
- 接口的本身反映了系統設計人員對系統的抽象理解
- 接口應有兩類:
- 第一類是對一個個體的抽象,它對應為一個抽象體(abstract class)
- 第二類是對一個個體某一方便的抽象,即形成一個抽象面(interface)
- 一個個體有可能有多個抽象面。抽象體和抽象面是有區別的。
三個面向區別
- 面向對象,我們考慮問題時,以對象為單位,考慮它的屬性及方法
- 面向過程,我們考慮問題時,以一個具體的流程(事務過程)為單位,考慮它的實現
- 接口設計與非接口設計是針對復用技術而言的,與面向對象(過程)不是一個問題。更多的體現就是對系統整體的架構。
8.2、使用注解開發
注解在接口上實現
public interface UserMapper {@Select("select * from user")List<User> getUserList(); }需要在核心配置文件中綁定接口
<mappers><mapper class="com.sue.dao.UserMapper"/> </mappers>測試
package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.HashMap; import java.util.List;public class UserMapperTest {@Testpublic void test(){SqlSession sqlSession = MyBatisUtil.getSqlSession();//底層主要用反射try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}}finally {if (sqlSession!=null){sqlSession.close();}}} }本質:反射機制實現
底層:動態代理
mybatis詳細的執行流程
8.3、CRUD
我們可以造工具類創建的時候實現自動提交事務!
public static SqlSession getSqlSession() {return sqlSessionFactory.openSession(true); }編寫接口,增加注解
import com.sue.pojo.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update;import java.util.List;/*** @Description: 接口描述* @Author: com.zyy* @Date: 2022/03/12 09:41*/ public interface UserMapper {@Select("select id, name, pwd from `user`")List<User> getUserList();@Select("select id, name, pwd 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); }【注意:我們必須要將接口注冊綁定到我們的核心配置文件中】
關于@Param()注解
- 基本類型的參數或者String類型,需要加上
- 引用類型不需要加
- 如果只有一個基本類型的話,可以忽略,但是建議大家都加上
- 我們在sql中引用的就是我們這里的@Param()中設定的屬性名
#{} ${}區別
參考博客
9、Lombok
使用步驟
在idea中安裝lombok插件
在項目中導入lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version> </dependency>在實體類上加注解即可
package com.sue.pojo;import lombok.Data;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.pojo* @ClassName : .java* @createTime : 2022/9/8 9:24* @Email : 1420779618@qq.com* @公眾號 :* @Website :* @Description :*/ @Data @AllArgsConstructor @NoArgsConstructor public class User {private int id;private String name;private String password;}注解
@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實現原理:
99%的程序員都在用Lombok,原理竟然這么簡單?我也手擼了一個!|建議收藏!!! - 云+社區 - 騰訊云 (tencent.com)
10、多對一處理
多對一:
- 多個學生,對應一個老師
- 對于學生而言, 關聯 ,多個學生,關聯一個老師【多對一】
- 對于老師而言, 集合 ,一個老師有很多學生【一對多】
SQL
CREATE TABLE `teacher` (`id` INT(10) NOT NULL,`name` VARCHAR(30) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE = INNODBDEFAULT 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 = INNODBDEFAULT 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');測試環境搭建
Student.java
@Data public class Student {private int id;private String name;private Teacher teacher; }Teacher.java
@Data public class Teacher {private int id;private String name; }按照查詢嵌套處理
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sue.dao.StudentMapper"><!--思路:1. 查詢所有的學生信息2. 根據查詢出來的學生的tid,尋找對應的老師 子查詢--><select id="getStudent" resultMap="studentTeacher">select *from student;</select><resultMap id="studentTeacher" type="Student"><!-- 復雜的屬性,我們需要單獨處理 對象:association 集合:collection --><association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/></resultMap><select id="getTeacher" resultType="Teacher">select *from teacherwhere id=#{id};</select></mapper>按照結果嵌套處理
<!-- 按照結果嵌套處理 --><select id="getStudent2" resultMap="studentTeacher2">select s.id sid,s.name sname,t.name tname,t.idfrom student s,teacher twhere 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"/><result property="id" column="id"/></association> </resultMap>回顧mysql多對一查詢方式:
- 子查詢
- 鏈表查詢
11、一對多處理
比如:一個老師擁有多個學生!
對于老師而言,就是一對多的關系!
環境搭建
實體類
@Data public class Student {private int id;private String name;//關聯一個老師private int tid;} @Data public class Teacher {private int id;private String name;//一個老師有多個學生private List<Student> students; }按照結果嵌套處理
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sue.dao.TeacherMapper"><!-- 按結果嵌套查詢 --><select id="getTeacher" resultMap="TeacherStudent">select s.id sid,s.name sname,t.name tname,t.id tidfrom teacher t ,student swhere s.tid=t.id and t.id=#{tid}</select><resultMap id="TeacherStudent" type="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/><!--復雜的屬性,我們需要單獨處理 集合:collectionjavaType="" 執行屬性的類型集合中的泛型信息,我們使用ofType獲取--><collection property="students" ofType="Student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection></resultMap></mapper>按照查詢嵌套處理
<select id="getTeacher2" resultMap="TeacherStudent2">select * from 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 student where tid=#{tid} </select>小結
- 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 = INNODBDEFAULT CHARSET = utf8;創建一個基礎工程
導包
編寫配置文件
編寫實體類
package com.sue.pojo;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;import java.util.Date;@Data @AllArgsConstructor @NoArgsConstructor public class Blog {private String id;private String title;private String author;private Date createTime;//屬性名和字段名不一致private int views;}編寫實體類對應Mapper接口和Mapper.xml文件
if
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sue.dao.BlogMapper"><insert id="addBlog" parameterType="Blog">insert into mybatis.blog(id, title, author, create_time, views)values (#{id},#{title},#{author},#{createTime},#{views});</insert><select id="queryBlogIF" parameterType="Map" resultType="Blog">select *from mybatis.blogwhere 1=1<if test="title!=null">and title=#{title}</if><if test="author!=null">and author=#{author}</if></select></mapper>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> <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>如果 where 元素與你期望的不太一樣,你也可以通過自定義 trim 元素來定制 where 元素的功能。比如,和 where 元素等價的自定義 trim 元素為:
<trim prefix="WHERE" prefixOverrides="AND |OR ">... </trim> <trim prefix="SET" suffixOverrides=",">... </trim>所謂的動態sql。本質還是sql語句,只是我們可以在sql層面,去執行一個邏輯代碼
SQL片段
有的時候,我們可能會將一些功能的部分抽取出來,方便復用
使用sql標簽抽取公共的部分
<sql id="title-author-views"><choose><when test="title != null">title like #{title}</when><when test="author != null">and author = #{author}</when><otherwise>and views=#{views}</otherwise></choose> </sql>在需要使用的地方使用include標簽引用即可
<select id="getBlogList" parameterType="map" resultType="com.sue.pojo.Blog">select id,title,author,create_time createTime,views from blog<where><include refid="title-author-views"/></where> </select>注意事項:
- 最好基于單表來定義sql片段
- 不要存在where標簽
foreach
<!--select id,title,author,create_time createTime,views from blog where 1=1 and (id ='1' or id='2'or id='3')--> <select id="getBlogListForeach" parameterType="map" resultType="com.sue.pojo.Blog">select id,title,author,create_time createTime,views from blog<where><foreach collection="idList" item="id" open="(" close=")" separator="or">id = #{id}</foreach></where> </select>動態sql就是在拼接sql語句,我們只要保證sql正確性,按照sql的格式,去排列組合就可以了
<select id="queryBlogForeach" parameterType="Map" resultType="Blog">select *from mybatis.blog<where><foreach collection="ids" item="id" open="and (" separator="or" close=")">id=#{id}</foreach></where> </select> SqlSession sqlSession = MyBatisUtil.getSqlSession(); try {BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);HashMap map = new HashMap();ArrayList<Integer> ids=new ArrayList<Integer>();ids.add(1);ids.add(2);map.put("ids", ids);List<Blog> blogs = mapper.queryBlogForeach(map);for (Blog blog : blogs) {System.out.println(blog);} } finally {if (sqlSession!=null){sqlSession.close();} }13、緩存
13.1、簡介
- 存在內存中的臨時數據
- 將用戶經常查詢的數據放在緩存(內存)中,用戶去查詢數據就不用從磁盤上(關系型數據庫數據文件)查詢,從緩存中查詢,從而提高查詢效率,解決了高并發系統的性能問題。
- 減少和數據庫的交互次數,減少系統開銷,提高系統效率
- 經常查詢并且不經常改變的數據
13.2、mybatis緩存
- mybatis包含一個非常強大的查詢緩存特性,它可以非常方便地定制和配置緩存。緩存可以極大的提高查詢效率。
- mybatis系統中默認定義了兩級緩存:一級緩存和二級緩存
- 默認情況下,只有一級緩存開啟。(sqlsession級別的緩存,也稱為本地緩存)
- 二級緩存需要手動開啟和配置,它是基于namespace級別的緩存。
- 為了提高擴展性,mybatis定義了緩存接口cache。我們可以通過實現cache接口來自定義二級緩存。
13.3、一級緩存
- 一級緩存也叫本次緩存
- 與數據庫同一次會話期間查詢到的數據會放到本次緩存中。
- 以后如果需要獲取相同的數據,直接從緩存中拿,沒必須再去查詢數據庫
開啟日志
測試再一個session中查詢兩次相同的記錄
package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;public class MyTest {@Testpublic void getUserById() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user1 = mapper.queryUserById(1);System.out.println(user1);System.out.println("==================");User user2 = mapper.queryUserById(1);System.out.println(user2);System.out.println(user1 == user2);} finally {if (sqlSession != null) {sqlSession.close();}}} }查詢日志輸出
緩存失效的情況:
查詢不同的Mapper.xml
手動清理緩存
package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;public class MyTest {@Testpublic void getUserById() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user1 = mapper.queryUserById(1);System.out.println(user1);System.out.println("==================");//手動清理緩存sqlSession.clearCache();User user2 = mapper.queryUserById(2);System.out.println(user2);System.out.println(user1 == user2);} finally {if (sqlSession != null) {sqlSession.close();}}} }小結:
- 一級緩存默認是開啟的,只在一次sqlsession中有效,也就是拿到連接到關閉了連接這個區間段!
- 一級緩存就是一個map
13.4、二級緩存
- 二級緩存也叫全局緩存,一級緩存作用域太低了,所以誕生了二級緩存。
- 基本namespace級別的緩存,一個名稱空間,對應一個二級緩存
- 工作機制
- 一個會話查詢一個數據,這個數據就會被放到當前會話的一級緩存中
- 如果當前會話關閉了,這個會話對應的一級緩存就沒了,但是我們想要的是,會話關閉了,一級緩存中的數據被保存到二級緩存中
- 新的會話查詢信息,就可以直接從二級緩存中獲取內容
- 不同的mapper查出的數據會放在自己對應的緩存(map)中
步驟
開啟全部緩存
mybatis-config.xml
<settings><setting name="logImpl" value="STDOUT_LOGGING"/><!-- 顯式開啟全局緩存--><setting name="cacheEnabled" value="true"/> </settings>在要使用二級緩存的mapper中開啟
<!-- 在當前mapper.xml中使用二級緩存--> <cache/>也可以自定義參數
<!-- 在當前mapper.xml中使用二級緩存--> <cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>測試
@Test public void getUserById2() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user1 = mapper.getUserById(1);System.out.println(user1);sqlSession.close();System.out.println("==================");SqlSession sqlSession2 = MybatisUtils.getSqlSession();UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);User user2 = mapper2.getUserById(1);System.out.println(user2);System.out.println(user1 == user2);sqlSession2.close(); }問題:我們需要將實體類序列化,否則就會報錯
Caused by: java.io.NotSerializableException: com.sue.pojo.User解決
public class User implements Serializable { }小結:
- 只要開啟了二級緩存,在同一個Mapper下就有效
- 所有的數據都會先放在一級緩存中
- 只有當會話提交或者關閉的時候,才會提交到二級緩存中。
13.5、緩存原理
結果如下
PooledDataSource forcefully closed/removed all connections. PooledDataSource forcefully closed/removed all connections. PooledDataSource forcefully closed/removed all connections. PooledDataSource forcefully closed/removed all connections. Cache Hit Ratio [com.sue.dao.UserMapper]: 0.0 Opening JDBC Connection Created connection 867398280. ==> Preparing: select id,name,pwd from user where id=? ==> Parameters: 1(Integer) <== Columns: id, name, pwd <== Row: 1, sue, 123456 <== Total: 1 User(id=1, name=zyy, pwd=123456) Cache Hit Ratio [com.sue.dao.UserMapper]: 0.0 User(id=1, name=sue, pwd=123456) true Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@33b37288] Returned connection 867398280 to pool. ================== Cache Hit Ratio [com.sue.dao.UserMapper]: 0.0 Opening JDBC Connection Checked out connection 867398280 from pool. ==> Preparing: select id,name,pwd from user where id=? ==> Parameters: 2(Integer) <== Columns: id, name, pwd <== Row: 2, 張三, 111111 <== Total: 1 User(id=2, name=張三, pwd=111111) Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@33b37288] Returned connection 867398280 to pool. ================== As you are using functionality that deserializes object streams, it is recommended to define the JEP-290 serial filter. Please refer to https://docs.oracle.com/pls/topic/lookup?ctx=javase15&id=GUID-8296D8E8-2B93-4B9A-856E-0A65AF9B8C66 Cache Hit Ratio [com.sue.dao.UserMapper]: 0.25 User(id=2, name=張三, pwd=111111) false13.6、自定義緩存-ehcache
Ehcache是一種廣泛使用的開源java分布式緩存,只要面向通用緩存。
要在程序中使用ehcache,先導包
<dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.1.0</version> </dependency>在mapper中指定使用我們的ehcache緩存實現
<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分為內存和磁盤兩級,此屬性定義磁盤的緩存位置。參數解釋如下:user.home – 用戶主目錄user.dir – 用戶當前工作目錄java.io.tmpdir – 默認臨時文件路徑--><diskStore path="./tmpdir/Tmp_EhCache"/><defaultCacheeternal="false"maxElementsInMemory="10000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="259200"memoryStoreEvictionPolicy="LRU"/><cachename="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>總結
以上是生活随笔為你收集整理的【SSM框架】MyBatis的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 双时推迟格林函数的定义
- 下一篇: jedis简介和使用