日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Mybatis-9.28

發(fā)布時間:2024/3/13 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Mybatis-9.28 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Mybatis-9.28

環(huán)境:

  • JDK 1.8
  • Mysql 5.7以上
  • maven 3.6.1
  • IDEA

回顧:

  • JDBC
  • Mysql
  • Java基礎(chǔ)
  • Maven
  • Junit

SSM框架:配置文件的,學習的最好方式:看官方文檔;

1、簡介

1.1、什么是Mybatis

  • MyBatis 是一款優(yōu)秀的持久層框架
  • 它支持自定義 SQL、存儲過程以及高級映射。
  • MyBatis 免除了幾乎所有的 JDBC 代碼以及設(shè)置參數(shù)和獲取結(jié)果集的工作。
  • MyBatis 可以通過簡單的 XML 或注解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)為數(shù)據(jù)庫中的記錄。
  • MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名為MyBatis 。
  • 2013年11月遷移到Github。

如何獲得Mybatis:

  • maven倉庫:

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.3</version> </dependency>
  • Github:https://github.com/mybatis/mybatis-3/releases/tag/mybatis-3.5.6

  • 中文文檔:https://mybatis.org/mybatis-3

1.2、持久化

數(shù)據(jù)持久化:

  • 持久化就是將程序的數(shù)據(jù)在持久狀態(tài)和瞬時狀態(tài)轉(zhuǎn)化的過程
  • 內(nèi)存:斷電即失
  • 數(shù)據(jù)庫(JDBC)、io文件持久化
  • 生活:冷藏、罐頭

為什么需要持久化:

  • 有一些對象,不能讓他丟掉
  • 內(nèi)存太貴

1.3、持久層

Dao層、Service層、Controllor層…

  • 完成持久化工作的代碼塊
  • 層界限十分明顯

1.4、為什么需要Mybatis

  • 方便
  • 幫助程序員將數(shù)據(jù)存入到數(shù)據(jù)庫中
  • 傳統(tǒng)的JDBC代碼太復(fù)雜了,簡化、框架、自動化
  • 更容易上手
  • 優(yōu)點:
    • 簡單易學
    • 靈活
    • sql和代碼的分離,提高了可維護性。
    • 提供映射標簽,支持對象與數(shù)據(jù)庫的orm字段關(guān)系映射
    • 提供對象關(guān)系映射標簽,支持對象關(guān)系組建維護
    • 提供xml標簽,支持編寫動態(tài)sql

2、第一個Mybatis程序

思路:搭建環(huán)境——>導(dǎo)入Mybatis——>編寫代碼——>測試

2.1、搭建環(huán)境

搭建數(shù)據(jù)庫:

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 );INSERT INTO user VALUES (1,'張三','123456'), (2,'李四','123456'), (3,'王五','123456'), (4,'趙六','123456'), (5,'桃七','123456');

新建項目:

  • 新建一個普通的maven項目

  • 刪除src目錄,形成父工程

  • 導(dǎo)入maven依賴

    <!--導(dǎo)入依賴--><dependencies><!--mysql驅(qū)動--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.22</version></dependency><!--mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.3</version></dependency><!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>
  • 2.2、創(chuàng)建一個模塊

    • 編寫mybatis的核心配置文件

      <!--configuration核心配置文件--> <configuration><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?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/><property name="username" value="root"/><property name="password" value="199819"/></dataSource></environment></environments></configuration>
    • 編寫mybatis工具類

      /*** SqlSessionFactory ----> sqlSession*/ public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;static {try {//第一步:使用Mybatis獲取SqlSessionFactory對象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}//既然有了 SqlSessionFactory,顧名思義,我們可以從中獲得 SqlSession 的實例。//SqlSession 提供了在數(shù)據(jù)庫執(zhí)行 SQL 命令所需的所有方法。你可以通過 SqlSession 實例來直接執(zhí)行已映射的 SQL 語句public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();} }

    2.3、編寫代碼

    • 實體類

      /*** 實體類*/ 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 + '\'' +", pwd='" + pwd + '\'' +'}';} }
    • Dao接口

      public interface UserDao {List<User> getUserList(); }
    • Dao接口實現(xiàn)類:由原來的UserDaoImpl轉(zhuǎn)換為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:綁定一個對應(yīng)的Dao/Mapper接口--> <mapper namespace="com.chen.dao.UserDao"><!--select查詢工具--><select id="getUserList" resultType="com.chen.pojo.User">select * from mybatis.user</select> </mapper>

    2.4、測試

    注意點:

    org.apache.ibatis.binding.BindingException: Type interface com.chen.dao.UserDao is not known to the MapperRegistry.

    MapperRegistry:在核心配置文件中注冊mappers

    • junit測試

      public class UserDaoTest {@Testpublic void test(){//mybatis-config.xml第一步:獲得SqlSession對象SqlSession sqlSession = MybatisUtils.getSqlSession();//第二步:方式一:執(zhí)行sqlUserDao mapper = sqlSession.getMapper(UserDao.class);List<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}//第三步:關(guān)閉SqlSessionsqlSession.close();} }

      可能會遇到的問題:

    • 配置文件沒有注冊
    • 綁定接口錯誤
    • 方法名不對
    • 返回類型不對
    • maven導(dǎo)出資源問題

    3、CURD

    **namespace:**namespace中的包名要和Dao/Mapper接口的包名一致;

    增刪改查的參數(shù)介紹:

    • id:就是對應(yīng)的namespace中的方法名;
    • resultType : Sql語句執(zhí)行的返回值;
    • parameterType : 參數(shù)類型;

    1、select

  • 編寫接口

    //查詢所有用戶List<User> getUserList();//根據(jù)id查詢用戶User getUserById(int id);
  • 編寫對應(yīng)的mapper中的sql語句

    <!--select查詢工具--><select id="getUserList" resultType="com.chen.pojo.User">select * from mybatis.user</select><select id="getUserById" parameterType="int" resultType="com.chen.pojo.User">select * from mybatis.user where id = #{id}</select>
  • 測試

    @Testpublic void getUserList(){//mybatis-config.xml第一步:獲得SqlSession對象SqlSession sqlSession = MybatisUtils.getSqlSession();//第二步:方式一:執(zhí)行sql 推薦使用方式一UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userList = mapper.getUserList();//第二步:方式二:執(zhí)行sql 已淘汰//List<User> userList = sqlSession.selectList("com.chen.dao.UserDao.getUserList");for (User user : userList) {System.out.println(user);}//第三步:關(guān)閉SqlSessionsqlSession.close();}@Testpublic void getUserById(){//獲得SqlSession對象SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.getUserById(1);System.out.println(user);//關(guān)閉SqlSessionsqlSession.close();}
  • 2、insert

    //插入一個用戶int addUser(User user); <!--對象中的屬性,可以直接寫出來--><insert id="addUser" parameterType="com.chen.pojo.User">insert into user(id,name,pwd) value (#{id},#{name},#{pwd});</insert> @Testpublic void addUser(){//獲得SqlSession對象SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int res = mapper.addUser(new User(6, "rose", "123333"));if (res > 0) {System.out.println("插入成功!");}//提交事物sqlSession.commit();//關(guān)閉SqlSessionsqlSession.close();}

    3、update

    //修改用戶 int updateUser(User user); <update id="updateUser" parameterType="com.chen.pojo.User">update user set name=#{name},pwd=#{pwd} where id = #{id}; </update> @Test public void updateUser(){//獲得SqlSession對象SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.updateUser(new User(4,"tom","123123"));//提交事物sqlSession.commit();//關(guān)閉SqlSessionsqlSession.close(); }

    4、delete

    //刪除一個用戶 int deleteUser(int id); <delete id="deleteUser" parameterType="int">delete from user where id = #{id}; </delete> @Test public void deleteUser(){//獲得SqlSession對象SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.deleteUser(4);//提交事物sqlSession.commit();//關(guān)閉SqlSessionsqlSession.close(); }

    **注意點:**增刪改需要提交事物;

    5、分析錯誤

    • 標簽不要匹配錯;
    • resource綁定mapper,需要使用路徑;
    • 程序配置文件必須符合規(guī)范;
    • maven資源沒有導(dǎo)出問題;

    6、萬能的Map

    假設(shè)我們的實體類、或者數(shù)據(jù)庫中的表、字段或者參數(shù)過多,我們應(yīng)當考慮使用Map!

    //插入一個用戶 int addUser2(Map<String,Object> map); <insert id="addUser2" parameterType="map">insert into user(id,name,pwd) value (#{userId},#{userName},#{userPassword}); </insert> @Test public void addUser2(){//獲得SqlSession對象SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);Map<String, Object> map = new HashMap<String, Object>();map.put("userId",4);map.put("userName","jack");map.put("userPassword","666777");mapper.addUser2(map);//提交事物sqlSession.commit();//關(guān)閉SqlSessionsqlSession.close(); }
  • Map傳遞參數(shù),直接在sql中取出key即可! 【parameterType=“map”】

  • 對象傳遞參數(shù),直接在sql中取出對象的屬性即可! 【parameterType=“Object”】

  • 只有一個基本類型參數(shù)的情況下,可以直接在sql中取到 多個參數(shù)用Map , 或者注解

  • 7、模糊查詢

  • java代碼執(zhí)行的時候,傳遞通配符 % %

    List<User> userList = mapper.getUserLike("%李%");
  • 在sql拼接中使用通配符 % %

    select * from user where name like "%"#{value}"%";
  • 4、配置解析

    4.1、核心配置文件

    • mybatis-config.xml
    • MyBatis 的配置文件包含了會深深影響 MyBatis 行為的設(shè)置和屬性信息。 配置文檔的頂層結(jié)構(gòu)如下:
      • configuration(配置)
        • properties(屬性)
        • settings(設(shè)置)
        • typeAliases(類型別名)
        • typeHandlers(類型處理器)
        • objectFactory(對象工廠)
        • plugins(插件)
        • environments(環(huán)境配置)
          • environment(環(huán)境變量)
            • transactionManager(事務(wù)管理器)
            • dataSource(數(shù)據(jù)源)
        • databaseIdProvider(數(shù)據(jù)庫廠商標識)
        • mappers(映射器)

    4.2、環(huán)境配置(environments)

    MyBatis 可以配置成適應(yīng)多種環(huán)境,這種機制有助于將 SQL 映射應(yīng)用于多種數(shù)據(jù)庫之中,不過要記住:盡管可以配置多個環(huán)境,但每個 SqlSessionFactory 實例只能選擇一種環(huán)境。

    學會使用配置多套運行環(huán)境:

    <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?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/><property name="username" value="root"/><property name="password" value="199819"/></dataSource></environment><environment id="test"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/><property name="username" value="root"/><property name="password" value="199819"/></dataSource></environment> </environments>

    注意一些關(guān)鍵點:

    • 默認使用的環(huán)境 ID(比如:default=“development”)。
    • 每個 environment 元素定義的環(huán)境 ID(比如:id=“development”)。
    • 事務(wù)管理器的配置(比如:type=“JDBC”)。
    • 數(shù)據(jù)源的配置(比如:type=“POOLED”)。

    默認環(huán)境和環(huán)境 ID 顧名思義。 環(huán)境可以隨意命名,但務(wù)必保證默認的環(huán)境 ID 要匹配其中一個環(huán)境 ID。

    MyBatis默認的事務(wù)管理器**(transactionManager)就是JDBC ;默認的連接池【數(shù)據(jù)源(dataSource)】**就是POOLED;

    4.3、屬性(properties)

    我們可以通過properties屬性來實現(xiàn)引用配置文件

    這些屬性可以在外部進行配置,并可以進行動態(tài)替換。你既可以在典型的 Java 屬性文件中配置這些屬性,也可以在 properties 元素的子元素中設(shè)置。【db.poperties】

    編寫一個db.properties配置文件(數(shù)據(jù)庫連接):

    #連接數(shù)據(jù)庫的4個屬性 driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8 username=root password=199819

    在核心配置文件中引入外部資源配置文件:

    <!--引入外部配置文件--><properties resource="db.properties"><property name="pwd" value="199819"/></properties>
  • 可以直接引入外部文件;
  • 可以在其中增加一些屬性配置;
  • 如果外部和內(nèi)部兩個文件有同一個字段,優(yōu)先使用外部配置文件的屬性;
  • 4.4、類型別名(typeAliases)

    • 類型別名可為 Java 類型設(shè)置一個縮寫名字
    • 它僅用于 XML 配置,意在降低冗余的全限定類名書寫
    <!--可以給實體類起別名--> <typeAliases><typeAlias type="com.chen.pojo.User" alias="User"/> </typeAliases>
    • 也可以指定一個包名,MyBatis 會在包名下面搜索需要的 Java Bean,掃描實體類的包,它的默認別名就是這個類的首字母小寫的類名;
    <!--也可以指定一個包名,MyBatis 會在包名下面搜索需要的 Java Bean--> <typeAliases><package name="com.chen.pojo"/> </typeAliases>

    在實體類比較少的時候,使用第一種方式;如果實體類比較多,建議使用第二種;

    區(qū)別:第一種可以自定義別名;第二種則不可以,如果非要改,需要在實體類上增加注解。

    @Alias("user") public class User {private int id;private String name;private String pwd; }

    4.5、設(shè)置(settings)

    這是 MyBatis 中極為重要的調(diào)整設(shè)置,它們會改變 MyBatis 的運行時行為。

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-aNDwa01D-1620831798579)(image/image-20210412213112008.png)]

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-kM6VWmlp-1620831798580)(image/image-20210412213140060.png)]

    4.5、其他配置

    • typeHandlers(類型處理器)
    • objectFactory(對象工廠)
    • plugins 插件
      • mybatis-generator-core
      • mybatis-plus
      • 通用mapper

    4.7、映射器(mappers)

    MapperRegistry:注冊綁定我們的Mapper文件;

    方式一:使用相對于類路徑的資源引用 【推薦使用:接口和他的Mapper配置文件可不同名、也可不在同一個包下】

    <!--每一個Mapper.xml都需要在Mybatis核心配置文件中注冊--> <mappers><mapper resource="com/chen/dao/UserMapper.xml"/> </mappers>

    方式二:使用映射器接口實現(xiàn)類的完全限定類名

    <!--每一個Mapper.xml都需要在Mybatis核心配置文件中注冊--> <mappers><mapper class="com.chen.dao.UserMapper"/> </mappers>

    注意點:

    • 接口和他的Mapper配置文件必須同名
    • 接口和他的Mapper配置文件必須在同一個包下

    方式三:將包內(nèi)的映射器接口實現(xiàn)全部注冊為映射器

    <!--每一個Mapper.xml都需要在Mybatis核心配置文件中注冊--> <mappers><package name="com.chen.dao"/> </mappers>

    注意點:

    • 接口和他的Mapper配置文件必須同名
    • 接口和他的Mapper配置文件必須在同一個包下

    7、生命周期和作用域

    聲明周期和作用域是至關(guān)重要的,因為錯誤的使用會導(dǎo)致非常嚴重的并發(fā)問題;

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-KDPaYNPb-1620831798582)(image/image-20210412220128046.png)]

    SqlSessionFactoryBuilder:

    • 一旦創(chuàng)建了SqlSessionFactory,就不再需要它了
    • 局部變量

    SqlSessionFactory:

    • 可以想象為:數(shù)據(jù)庫連接池
    • SqlSessionFactory一旦被創(chuàng)建就應(yīng)該在應(yīng)用的運行期間一直存在,沒有任何理由丟棄它或重新創(chuàng)建一個實例。
    • 因此SqlSessionFactory的最佳作用域是應(yīng)用作用域(ApplocationContext)。
    • 最簡單的就是使用單例模式或靜態(tài)單例模式。

    SqlSession:

    • 連接到連接池的一個請求
    • SqlSession 的實例不是線程安全的,因此是不能被共享的,所以它的最佳的作用域是請求或方法作用域。
    • 用完之后需要趕緊關(guān)閉,否則資源被占用!
    • [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-JJ1jRcBZ-1620831798583)(image/image-20210412220753109.png)]
    • 這里面的每一個Mapper,就代表一個具體的業(yè)務(wù)!

    5、解決屬性名和字段名不一致的問題

    數(shù)據(jù)庫中的字段:

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-h4SIZrS7-1620831798585)(image/image-20210416203516340.png)]

    新建一個項目,測試實體類字段不一致的情況:

    public class User {private int id;private String name;private String pwd; }

    實際上的sql語句:

    select * from mybatis.user where id = #{id} 等價于: select id,name,pwd from mybatis.user where id = #{id}

    測試發(fā)現(xiàn)問題:因為數(shù)據(jù)庫中無password,只有pwd:

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-RzLf19Ry-1620831798586)(image/image-20210416204928184.png)]

    解決方法:

  • 起別名

    <select id="getUserById" parameterType="int" resultType="User">select id,name,pwd as password from mybatis.user where id = #{id} </select>
  • resultMap:結(jié)果集映射

    也可以只映射字段屬性不一致的

    <select id="getUserById" resultMap="UserMap">select * from mybatis.user where id = #{id}</select><!--結(jié)果集映射--><resultMap id="UserMap" type="User"><!--property:實體類中的屬性column:數(shù)據(jù)庫中的字段id:主鍵 result:其他屬性--><id property="id" column="id"/><result property="name" column="name"/><result property="password" column="pwd"/></resultMap>
    • resultMap 元素是 MyBatis 中最重要最強大的元素.
    • ResultMap 的設(shè)計思想是,對簡單的語句做到零配置,對于復(fù)雜一點的語句,只需要描述語句之間的關(guān)系就行了。
    • ResultMap 的優(yōu)秀之處——你完全可以不用顯式地配置它們。
    • 如果這個世界總是這么簡單就好了。

    6、日志

    6.1、日志工廠

    如果一個數(shù)據(jù)庫操作出現(xiàn)了異常,我們需要排錯,日志就是最好的助手!

    曾經(jīng):sout、debug

    現(xiàn)在:日志工廠

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-rsrVz77m-1620831798587)(image/image-20210416213741690.png)]

    • SLF4J
    • LOG4J 【掌握】
    • LOG4J2
    • JDK_LOGGING
    • COMMONS_LOGGING
    • STDOUT_LOGGING 【掌握】
    • NO_LOGGING

    在Mybatis中具體使用那個日志,在設(shè)置中設(shè)定!

    **STDOUT_LOGGING :**標準日志輸出

    • 在Mybatis核心配置文件中配置我們的日志:

      <settings><!--標準日志:不需要導(dǎo)入包直接用--><setting name="logImpl" value="STDOUT_LOGGING"/></settings>

      [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-ZBhZlmou-1620831798587)(image/image-20210416214645953.png)]

    6.2、log4j

    什么是Log4j?

    • Log4j是Apache的一個開源項目,通過使用Log4j,我們可以控制日志信息輸送的目的地是控制臺、文件、GUI組件;
    • 我們也可以控制每一條日志的輸出格式;
    • 通過定義每一條日志信息的級別,我們能夠更加細致地控制日志的生成過程;
    • 最令人感興趣的就是,這些可以通過一個配置文件來靈活地進行配置,而不需要修改應(yīng)用的代碼。

    1.先導(dǎo)入log4j的包

    <dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version> </dependency>

    2.log4j.properties

    #將等級為DEBUG的日志信息輸出到console和file這兩個目的地,console和file的定義在下面的代碼 log4j.rootLogger=DEBUG,console,file#控制臺輸出的相關(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/rzp.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.sq1.PreparedStatement=DEBUG

    3.配置settings為log4j實現(xiàn)

    <settings><setting name="logImpl" value="LOG4J"/> </settings>

    4.測試運行

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-3plSlGxC-1620831798588)(image/image-20210416215800129.png)]

    Log4j簡單使用

    1.在測試類中要使用Log4j的類中,導(dǎo)入包 import org.apache.log4j.Logger;

    2.日志對象,參數(shù)為當前類的class對象;

    Logger logger = Logger.getLogger(UserDaoTest.class);

    3.日志級別;

    Logger logger = Logger.getLogger(UserMapper.class); @Testpublic void testLog4j(){logger.info("info:進入了log4j");logger.debug("debug:進入了log4j");logger.error("error:進入了log4j");}

    7、分頁

    思考:為什么分頁?

    • 減少數(shù)據(jù)的處理量

    7.1、 使用Limit分頁

    語法:SELECT * from user limit startIndex,pageSize; select * from user limit 3; [0,n]

    使用MyBatis實現(xiàn)分頁,核心SQL:

    1.接口

    //分頁 List<User> getUserByLimit(Map<String,Integer> map);

    2.Mapper.xml

    <!--結(jié)果集映射--><resultMap id="UserMap" type="User"><!--property:實體類中的屬性column:數(shù)據(jù)庫中的字段id:主鍵 result:其他屬性--><id property="id" column="id"/><result property="name" column="name"/><result property="password" column="pwd"/></resultMap><!--分頁--><select id="getUserByLimit" parameterType="map" resultMap="UserMap">select * from user limit #{startIndex},#{pageSize};</select>

    3.測試

    @Testpublic void getUserByLimit(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String, Integer> map = new HashMap<String, Integer>();map.put("startIndex",0);map.put("pageSize",4);List<User> userByLimit = mapper.getUserByLimit(map);for (User user : userByLimit) {System.out.println(user);}}

    7.2 、RowBounds分頁

    不再使用SQL實現(xiàn)分頁
    1.接口

    //分頁2List<User> getUserByRowBounds();

    2.mapper.xml

    <!--分頁2--><select id="getUserByRowBounds" resultMap="UserMap">select * from user;</select>

    3.測試

    /*了解即可*/@Testpublic void getUserByRowBounds(){SqlSession sqlSession = MybatisUtils.getSqlSession();//RowBounds實現(xiàn)分頁RowBounds rowBounds = new RowBounds(1,3);//通過Java代碼層實現(xiàn)分頁List<User> users = sqlSession.selectList("com.chen.dao.UserMapper.getUserByRowBounds",null,rowBounds);for (User user : users) {System.out.println(user);}sqlSession.close();}

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-IKHarapN-1620831798589)(image/image-20210416223819205.png)]

    7.3 分頁插件

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-15yZh07k-1620831798589)(image/image-20210416223910970.png)]

    了解即可,萬一以后到公司使用到,需要知道是什么東西!

    8、使用注解開發(fā)

    8.1、面向接口編程

    面向接口編程的根本原因:解耦,可拓展,提高復(fù)用,分層開發(fā)中、上層不用管具體的實現(xiàn),大家都遵守共同的標準,使得開發(fā)變得容易,規(guī)范性好;

    關(guān)于抽象的理解:

    • 接口應(yīng)是定義(規(guī)范、約束)與實現(xiàn)的分離。
    • 接口本身反映了系統(tǒng)設(shè)計人員對系統(tǒng)的抽象理解。
    • 接口應(yīng)有兩類:
      • 第一類是對個體的抽象,可對應(yīng)為一個抽象體(abstract cass);
      • 第二類是對一個個體的某一方面的抽象(interface);
    • 一個個體可能有多個抽象面,抽象體和抽象面是有區(qū)別的。

    三個面向區(qū)別:

    • 面向?qū)ο笫侵?#xff0c;我們考慮問題時,以對象為單位,考慮它的屬性和方法;
    • 面向過程是指,我們考慮問題時,以一個具體的流程(事務(wù)過程)為單位,考慮它的實現(xiàn);
    • 接口設(shè)計與非接口設(shè)計是針對復(fù)用技術(shù)而言的,與面向?qū)ο?#xff08;過程)不是一個問題,更多的體現(xiàn)就是對系統(tǒng)整體的架構(gòu);

    8.2、使用注解開發(fā)

    1.注解在接口上實現(xiàn)

    public interface UserMapper {@Select("select * from user")List<User> getUsers(); }

    2.需要在核心配置文件中綁定接口

    <!--每一個Mapper.xml都需要在Mybatis核心配置文件中注冊--><mappers><!--綁定接口--><mapper class="com.chen.dao.UserMapper"/></mappers>

    3.測試

    @Test public void test1(){SqlSession sqlSession = MybatisUtils.getSqlSession();//底層主要應(yīng)用反射UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> users = mapper.getUsers();for (User user : users) {System.out.println(user);} }

    本質(zhì):反射機制實現(xiàn)

    底層:動態(tài)代理

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-btOgvGVW-1620831798590)(image/image-20210419190358176.png)]

    MyBatis詳細執(zhí)行流程:

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Nn27ODtg-1620831798590)(image/image-20210419191056320.png)]

    8.3、CRUD

    我們可以在工具類創(chuàng)建的時候?qū)崿F(xiàn)自動提交事物!

    public static SqlSession getSqlSession(){return sqlSessionFactory.openSession(true); //自動提交事物 }

    編寫接口,增加注解:

    //方法存在多個參數(shù),所有的參數(shù)前面必須加上@Param("id")注解 @Select("select * from user where id = #{id} and name = #{name}") User getUserById(@Param("id") int id, @Param("name") String name);@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})") 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);

    測試類:

    @Test public void test2(){SqlSession sqlSession = MybatisUtils.getSqlSession();//底層主要應(yīng)用反射UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.getUserById(1, "張三");System.out.println(user);sqlSession.close(); }@Test public void test3(){SqlSession sqlSession = MybatisUtils.getSqlSession();//底層主要應(yīng)用反射UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.addUser(new User(10, "hello", "188819"));sqlSession.close(); }@Test public void test4(){SqlSession sqlSession = MybatisUtils.getSqlSession();//底層主要應(yīng)用反射UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.updateUser(new User(10, "tom", "177898"));sqlSession.close(); }@Test public void test5(){SqlSession sqlSession = MybatisUtils.getSqlSession();//底層主要應(yīng)用反射UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.deleteUser(10);sqlSession.close(); }

    注意:我們必須將接口注冊綁定到我們的核心配置文件中!

    關(guān)于@Param("")注解

    • 基本類型的參數(shù)或者String類型,需要加上;
    • 引用類型不需要加;
    • 如果只有一個基本類型的話,可以忽略,但是建議大家都加上;
    • 我們在SQL中引用的就是我們這里的@Param("")中設(shè)定的屬性名;
    • #{} 和 ${}

    9、Lombok

    Lombok項目是一個Java庫,它會自動插入編輯器和構(gòu)建工具中,Lombok提供了一組有用的注釋,用來消除Java類中的大量樣板代碼。僅五個字符(@Data)就可以替換數(shù)百行代碼從而產(chǎn)生干凈,簡潔且易于維護的Java類。

    使用步驟:

  • 在IDEA中安裝Lombok插件

  • 在項目中導(dǎo)入lombok的jar包

    <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version><scope>provided</scope> </dependency>
  • 在程序上加注解

    @Getter and @Setter @FieldNameConstants @ToString @EqualsAndHashCode @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog @Data @Builder @SuperBuilder @Singular @Delegate @Value @Accessors @Wither @With @SneakyThrows @val
  • @Data注解:包含無參構(gòu)造、get、get、toString、hashCode、equals

  • 說明:

    @Data @AllArgsConstructor @NoArgsConstructor public class User {private int id;private String name;private String password; }
  • [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-LLtV4gKG-1620831798591)(image/image-20210419201501901.png)]

    10、多對一的處理

    多對一:多個學生對應(yīng)一個老師

    • 對于學生而言,關(guān)聯(lián):多個學生關(guān)聯(lián)一個老師【多對一】
    • 對于老師而言,集合:一個老師有很多學生【一對多】

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-u4sWhI4h-1620831798591)(image/image-20210419201909942.png)]

    10.1 測試環(huán)境搭建

    CREATE TABLE teacher( id int(10) Not null, name VARCHAR(30) DEFAULT NULL, PRIMARY KEY (id) )ENGINE=INNODB DEFAULT CHARSET=utf8INSERT 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=utf8INSERT INTO student VALUES (1,'小明',1), (2,'小紅',1), (3,'小張',1), (4,'小李',1), (5,'小王',1);
  • 導(dǎo)入lombok
  • 新建實體類Teacher,Student
  • 建立Mapper接口
  • 建立Mapper.xml文件
  • 在核心配置文件中綁定注冊我們的Mapper接口或者文件 【方式很多,隨心選】
  • 測試查詢是否能夠成功
  • 10.2、 按照查詢嵌套處理(子查詢)

    <!--思路:1. 查詢所有的學生信息2. 根據(jù)查詢出來的學生的tid尋找特定的老師 (子查詢)--><select id="getStudent" resultMap="studentTeacher">select * from student;</select><resultMap id="studentTeacher" type="student"><id property="id" column="id"/><result property="name" column="name"/><!--復(fù)雜的屬性,我們需要單獨列出來對象:用association集合:用collection--><association property="teacher" column="tid" javaType="teacher" select="getTeacher"/></resultMap><select id="getTeacher" resultType="teacher">select * from teacher where id=#{id}</select>

    10.3、按照結(jié)果嵌套處理(推薦使用)

    <!--按照結(jié)果嵌套處理--><select id="getStudent2" resultMap="studentTeacher2">SELECT s.id sid, s.name sname,t.name tname, t.id tidFROM student s, teacher tWHERE s.tid = t.id;</select><!--結(jié)果封裝,將查詢出來的列封裝到對象屬性中--><resultMap id="studentTeacher2" type="student"><id property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="teacher"><id property="id" column="tid"/><result property="name" column="tname"/></association></resultMap>

    回顧Mysql多對一查詢方式:

    • 子查詢 (按照查詢嵌套)
    • 聯(lián)表查詢 (按照結(jié)果嵌套)

    11、一對多處理

    一對多:一個老師擁有多個學生

    • 對于學生而言,關(guān)聯(lián):多個學生關(guān)聯(lián)一個老師【多對一】
    • 對于老師而言,集合:一個老師有很多學生【一對多】

    11.1、環(huán)境搭建

    實體類:

    @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; }

    11.2、 按照查詢嵌套處理(子查詢)

    <!--按照查詢嵌套處理(子查詢)--> <select id="getTeacherStudent2" resultMap="TeacherStudent2">select * from teacher where id = #{tid}; </select><resultMap id="TeacherStudent2" type="teacher"><id property="id" column="id"/><result property="name" column="name"/><collection property="students" column="id" javaType="ArrayList" ofType="student" select="getStudentByTeacherId"/> </resultMap><select id="getStudentByTeacherId" resultType="student">select * from student where tid = #{tid}; </select>

    11.3、按照結(jié)果嵌套處理(推薦使用)

    <!--按結(jié)果嵌套查詢--> <select id="getTeacherStudent" resultMap="TeacherStudent">select s.id sid,s.name sname,t.name tname,t.id tidfrom student s,teacher twhere s.tid = t.id and t.id = #{tid}; </select> <resultMap id="TeacherStudent" type="teacher"><id property="id" column="tid"/><result property="name" column="tname"/><!--復(fù)雜的屬性,我們需要單獨列出來對象:用association集合:用collectionjavaType="" 指定屬性的類型集合中的泛型信息,我們使用ofType獲取--><collection property="students" ofType="student"><id property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection> </resultMap>

    小結(jié):

    • 關(guān)聯(lián) - association 【多對一】 多個老師關(guān)聯(lián)一個學生[關(guān)聯(lián)]
    • 集合 - collection 【一對多】 一個老師有多個學生[集合]
    • javaType & ofType的區(qū)別:
      • JavaType用來指定實體類中的類型
      • ofType用來指定映射到List或者集合中的pojo類型,泛型中的約束類型

    注意點:

    • 保證SQL的可讀性,盡量保證通俗易懂
    • 注意一對多和多對一,屬性名和字段的問題
    • 如果問題不好排查錯誤,可以使用日志,建議使用Log4j

    面試高頻

  • Mysql引擎
  • InnoDB底層原理
  • 索引
  • 索引優(yōu)化
  • 12、動態(tài)SQL

    什么是動態(tài)SQL:動態(tài)SQL就是根據(jù)不同的條件生成不同的SQL語句;

    所謂的動態(tài)SQL,本質(zhì)上還是SQL語句,只是我們可以在SQL層面,去執(zhí)行一個邏輯代碼;

    動態(tài) SQL 是 MyBatis 的強大特性之一。如果你使用過 JDBC 或其它類似的框架,你應(yīng)該能理解根據(jù)不同條件拼接 SQL 語句有多痛苦,例如拼接時要確保不能忘記添加必要的空格,還要注意去掉列表最后一個列名的逗號。利用動態(tài) SQL,可以徹底擺脫這種痛苦。

    如果你之前用過 JSTL 或任何基于類 XML 語言的文本處理器,你對動態(tài) SQL 元素可能會感覺似曾相識。在 MyBatis 之前的版本中,需要花時間了解大量的元素。借助功能強大的基于 OGNL 的表達式,MyBatis 3 替換了之前的大部分元素,大大精簡了元素種類,現(xiàn)在要學習的元素種類比原來的一半還要少。- if - choose (when, otherwise) - trim (where, set) - foreach

    12.1、環(huán)境搭建

    CREATE TABLE `mybatis`.`blog` (`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '博客id',`title` varchar(30) NOT NULL COMMENT '博客標題',`author` varchar(30) NOT NULL COMMENT '博客作者',`create_time` datetime(0) NOT NULL COMMENT '創(chuàng)建時間',`views` int(30) NOT NULL COMMENT '瀏覽量',PRIMARY KEY (`id`) )

    創(chuàng)建一個基礎(chǔ)工程的要素:

  • 導(dǎo)包

  • 編寫配置文件

  • 編寫實體類

    @Data public class Blog {private int id;private String title;private String author;//這個字段與屬性名不一致需要處理private Date createTime;private int views; }
  • 編寫實體類對應(yīng)Mapper接口和Mapper.xml文件

  • 12.2、IF

  • 接口

    //查詢博客,如果輸入title或author則查詢相關(guān)的博客,//如果沒有輸入則查詢所有List<Blog> queryBlogIF(Map map);
  • 實體類

    @Data public class Blog {private String id;private String title;private String author;//這個字段與屬性名不一致需要處理private Date createTime;private int views; }
  • Mapper.xml

    <select id="queryBlogIF" parameterType="blog" resultType="blog"> select * from blog where 1=1 <if test="title != null">and title = #{title} </if> <if test="author != null">and author = #{author} </if> </select>

    改造后:

    <select id="queryBlogIF" parameterType="blog" resultType="blog"> select * from blog <where><if test="title != null">title = #{title}</if><if test="author != null">and author = #{author}</if> </where> </select>
  • 測試類

    @Test public void queryBlogIF(){SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);HashMap map = new HashMap();map.put("title","Mybatis");map.put("author","陳永瑞");List<Blog> blogs = mapper.queryBlogIF(map);for (Blog blog : blogs) {System.out.println(blog);} }
  • 12.3、choose (when, otherwise)

    <select id="queryBlogChose" parameterType="blog" resultType="blog">select * from 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>

    12.4、trim (where, set)

    **where:**where元素只會在子元素返回任何內(nèi)容的情況下才插入 “WHERE” 子句。而且,若子句的開頭為 “AND” 或 “OR”,where 元素也會將它們?nèi)コ?/p> <select id="queryBlogIF" parameterType="blog" resultType="blog"> select * from blog <where><if test="title != null">title = #{title}</if><if test="author != null">and author = #{author}</if> </where> </select>

    **set:**set元素會動態(tài)地在行首插入 SET 關(guān)鍵字,并會刪掉額外的逗號(這些逗號是在使用條件語句給列賦值時引入的)。

    <update id="updateBlog" parameterType="map">update blog<set><if test="title != null">title = #{title},</if><if test="author != null">author = #{author}</if></set>where id = #{id} </update>

    12.5、SQL片段

    有的時候,我們可能會將一些功能的部分抽取出來,方便復(fù)用!

    1.使用sql標簽抽取公共部分

    <sql id="if-title-author"><if test="title != null">title = #{title}</if><if test="author != null">and author = #{author}</if></sql>

    2.在需要使用的地方使用Include標簽引用即可

    <select id="queryBlogIF" parameterType="blog" resultType="blog">select * from blog<where><include refid="if-title-author"></include></where></select>

    注意事項:

    • 最好基于單表來定義SQL片段;
    • 不要存在where標簽;

    12.5、foreach

    你可以將任何可迭代對象(如 List、Set 等)、Map 對象或者數(shù)組對象作為集合參數(shù)傳遞給 foreach。當使用可迭代對象或者數(shù)組時,index 是當前迭代的序號,item 的值是本次迭代獲取到的元素。當使用 Map 對象(或者 Map.Entry 對象的集合)時,index 是鍵,item 是值。

    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 id="selectPostIn" resultType="domain.blog.Post">SELECT *FROM POST PWHERE ID in<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}</foreach> </select>

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-FmHUlyJe-1620831798592)(image/image-20210424092105470.png)]

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-GD93BMql-1620831798593)(image/image-20210424092714476.png)]

  • 接口

    //查詢第1-2-3號記錄的博客 List<Blog> queryBlogForeach(Map map);
  • Mapper.xml

    <!--select * from blog where 1=1 and (id=1,id=2,id=3)我們現(xiàn)在傳遞一個萬能的Map,這map中可以存在一個集合!open:開始close:結(jié)束separator:分割 --> <select id="queryBlogForeach" 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 queryBlogForeach(){SqlSession sqlSession = MybatisUtils.getSqlSession();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);}sqlSession.close(); }
  • 動態(tài)SQL就是在拼接SQL語句,我們只要保證SQL的正確性,按照SQL的格式,去排列組合就可以了

    **建議:**先在Mysql中寫出完整的SQL,再對應(yīng)的去修改成我們的動態(tài)SQL實現(xiàn)通用即可

    13、緩存

    13.1 簡介

    查詢 : 連接數(shù)據(jù)庫,耗資源 一次查詢的結(jié)果,給他暫存一個可以直接取到的地方 --> 內(nèi)存:緩存我們再次查詢的相同數(shù)據(jù)的時候,直接走緩存,不走數(shù)據(jù)庫了;

    1.什么是緩存Cache?

    • 存在內(nèi)存中的臨時數(shù)據(jù)
    • 將用戶經(jīng)常查詢的數(shù)據(jù)放在緩存(內(nèi)存)中,用戶去查詢數(shù)據(jù)就不用從磁盤上(關(guān)系型數(shù)據(jù)庫文件)查詢,從緩存中查詢,從而提高查詢效率,解決了高并發(fā)系統(tǒng)的性能問題

    2.為什么使用緩存?

    • 減少和數(shù)據(jù)庫的交互次數(shù),減少系統(tǒng)開銷,提高系統(tǒng)效率

    3.什么樣的數(shù)據(jù)可以使用緩存?

    • 經(jīng)常查詢并且不經(jīng)常改變的數(shù)據(jù) 【可以使用緩存】

    13.2 MyBatis緩存

    • MyBatis包含一個非常強大的查詢緩存特性,它可以非常方便的定制和配置緩存,緩存可以極大的提高查詢效率。
    • MyBatis系統(tǒng)中默認定義了兩級緩存:一級緩存二級緩存
      • 默認情況下,只有一級緩存開啟(SqlSession級別的緩存,也稱為本地緩存)
      • 二級緩存需要手動開啟和配置,他是基于namespace級別的緩存
      • 為了提高可擴展性,MyBatis定義了緩存接口Cache。我們可以通過實現(xiàn)Cache接口來定義二級緩存

    13.3 一級緩存

    • 一級緩存也叫本地緩存:SqlSession
      • 與數(shù)據(jù)庫同一次會話期間查詢到的數(shù)據(jù)會放在本地緩存中
      • 以后如果需要獲取相同的數(shù)據(jù),直接從緩存中拿,沒必要再去查詢數(shù)據(jù)庫

    測試步驟:

    1.開啟日志

    2.測試在一個Session中查詢兩次記錄

    public class MyTest {@Testpublic void queryUsersByID() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.queryUsersByID(1);System.out.println(user);System.out.println("----------------------------");User user1 = mapper.queryUsersByID(1);System.out.println(user1);System.out.println("----------------------------");System.out.println(user==user1);sqlSession.close();} }

    3.查看日志輸出
    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-wOOyquOu-1620831798593)(image/image-20210424151239221.png)]

    緩存失效的情況:

  • 兩次查詢不同的東西

  • 增刪改操作,可能會改變原來的數(shù)據(jù),所以必定會刷新緩存

    @Test public void updateUser() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.queryUsersByID(1);System.out.println(user);mapper.updateUser(new User(2,"aaaa","bbbb"));System.out.println("----------------------------");User user1 = mapper.queryUsersByID(1);System.out.println(user1);System.out.println("----------------------------");System.out.println(user==user1);sqlSession.close(); }

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-URSRrYpH-1620831798594)(image/image-20210424152230924.png)]

  • 查詢不同的Mapper.xml

  • 手動清理緩存

    @Test public void test() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.queryUsersByID(1);System.out.println(user);sqlSession.clearCache();//手動清理緩存System.out.println("----------------------------");User user1 = mapper.queryUsersByID(1);System.out.println(user1);System.out.println("----------------------------");System.out.println(user==user1);sqlSession.close(); }

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-qAjT6FVH-1620831798595)(image/image-20210424152455296.png)]

  • 13.4 二級緩存

    • 二級緩存也叫全局緩存,一級緩存作用域太低了,所以誕生了二級緩存

    • 基于namespace級別的緩存,一個名稱空間,對應(yīng)一個二級緩存

    • 工作機制

      • 一個會話查詢一條數(shù)據(jù),這個數(shù)據(jù)就會被放在當前會話的一級緩存中
      • 如果會話關(guān)閉了,這個會員對應(yīng)的一級緩存就沒了;但是我們想要的是,會話關(guān)閉了,一級緩存中的數(shù)據(jù)被保存到二級緩存中
      • 新的會話查詢信息,就可以從二級緩存中獲取內(nèi)容
      • 不同的mapper查詢出的數(shù)據(jù)會放在自己對應(yīng)的緩存(map)中
    • 一級緩存開啟(SqlSession級別的緩存,也稱為本地緩存)

    • 二級緩存需要手動開啟和配置,他是基于namespace級別的緩存。

    • 為了提高可擴展性,MyBatis定義了緩存接口Cache。我們可以通過實現(xiàn)Cache接口來定義二級緩存。

    步驟:

    1.開啟全局緩存

    <!--顯示的開啟全局(二級)緩存--> <setting name="cacheEnabled" value="true"/>

    2.在要使用二級緩存的Mapper.xml中開啟

    <!--在當前Mapper.xml中使用二級緩存--><cache/>

    也可以自定義一些參數(shù)

    <!--在當前Mapper.xml中使用二級緩存--><cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>

    3.實體類需實現(xiàn)序列號接口

    @Data @NoArgsConstructor @AllArgsConstructor public class User implements Serializable {private int id;private String name;private String pwd; }

    4.測試

    @Testpublic void test2() {SqlSession sqlSession1 = MybatisUtils.getSqlSession();SqlSession sqlSession2 = MybatisUtils.getSqlSession();UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);User user1 = mapper1.queryUsersByID(1);System.out.println(user1);sqlSession1.close();System.out.println("----------------------------");UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);User user2 = mapper2.queryUsersByID(1);System.out.println(user2);System.out.println("----------------------------");System.out.println(user1==user2);sqlSession2.close();}

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-0TX2GL42-1620831798596)(image/image-20210424154627019.png)]

    **問題:**我們需要將實體類序列化,否則就會報錯;

    小結(jié):

    • 只要開啟了二級緩存,在同一個Mapper下就有效
    • 所有的數(shù)據(jù)都會放在一級緩存中
    • 只有當前會話提交,或者關(guān)閉的時候,才會提交到二級緩存中

    13.5 緩存原理

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-ZepxnxTT-1620831798596)(image/image-20210424155105971.png)]
    注意:

    • 只有查詢才有緩存,根據(jù)數(shù)據(jù)是否需要緩存(修改是否頻繁選擇是否開啟)useCache=“true”
    <select id="getUserById" resultType="user" useCache="true">select * from user where id = #{id}</select>

    13.6 自定義緩存-ehcache

    Ehcache是一種廣泛使用的開源Java分布式緩存。主要面向通用緩存;

    要使用ehcache緩存的步驟:

    1.導(dǎo)包

    <dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.2.1</version> </dependency>

    2.在mapper中指定使用我們的ehcache緩存實現(xiàn)

    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> xml中開啟```java <!--在當前Mapper.xml中使用二級緩存--><cache/>

    也可以自定義一些參數(shù)

    <!--在當前Mapper.xml中使用二級緩存--><cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>

    3.實體類需實現(xiàn)序列號接口

    @Data @NoArgsConstructor @AllArgsConstructor public class User implements Serializable {private int id;private String name;private String pwd; }

    4.測試

    @Testpublic void test2() {SqlSession sqlSession1 = MybatisUtils.getSqlSession();SqlSession sqlSession2 = MybatisUtils.getSqlSession();UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);User user1 = mapper1.queryUsersByID(1);System.out.println(user1);sqlSession1.close();System.out.println("----------------------------");UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);User user2 = mapper2.queryUsersByID(1);System.out.println(user2);System.out.println("----------------------------");System.out.println(user1==user2);sqlSession2.close();}

    [外鏈圖片轉(zhuǎn)存中…(img-0TX2GL42-1620831798596)]

    **問題:**我們需要將實體類序列化,否則就會報錯;

    小結(jié):

    • 只要開啟了二級緩存,在同一個Mapper下就有效
    • 所有的數(shù)據(jù)都會放在一級緩存中
    • 只有當前會話提交,或者關(guān)閉的時候,才會提交到二級緩存中

    13.5 緩存原理

    [外鏈圖片轉(zhuǎn)存中…(img-ZepxnxTT-1620831798596)]
    注意:

    • 只有查詢才有緩存,根據(jù)數(shù)據(jù)是否需要緩存(修改是否頻繁選擇是否開啟)useCache=“true”
    <select id="getUserById" resultType="user" useCache="true">select * from user where id = #{id}</select>

    13.6 自定義緩存-ehcache

    Ehcache是一種廣泛使用的開源Java分布式緩存。主要面向通用緩存;

    要使用ehcache緩存的步驟:

    1.導(dǎo)包

    <dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.2.1</version> </dependency>

    2.在mapper中指定使用我們的ehcache緩存實現(xiàn)

    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

    總結(jié)

    以上是生活随笔為你收集整理的Mybatis-9.28的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。