Mybatis框架-基礎

Mybatis

環境:

  • JDK1.8
  • Mysql 5.7
  • maven 3.6.1
  • IDEA

學習Mybatis框架最好的方式:看官網文檔 https://mybatis.org/mybatis-3/zh/index.html;

1、簡介

1.1、什麼是Mybatis

在這裏插入圖片描述

  • MyBatis 是一款優秀的持久層框架
  • 它支持定製化 SQL、存儲過程以及高級映射
  • MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集
  • MyBatis 可以使用簡單的 XML 或註解來配置和映射原生類型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 對象)爲數據庫中的記錄
  • MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名爲MyBatis
  • 2013年11月遷移到Github

如何獲得Mybatis?

  • maven倉庫:

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</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層,Service層,Controller層….

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

1.4 爲什麼需要Mybatis?

  • 幫助程序猿將數據存入到數據庫中
  • 方便
  • 傳統的JDBC代碼太複雜了。簡化。框架。自動化
  • 不用Mybatis也可以, 技術沒有高低之分
  • 優點:
    • 簡單易學
    • 靈活
    • sql和代碼的分離,提高了可維護性
    • 提供映射標籤,支持對象與數據庫的orm字段關係映射
    • 提供對象關係映射標籤,支持對象關係組建維護
    • 提供xml標籤,支持編寫動態sql

最重要的一點:SSM使用的人多!

Spring SpringMVC SpringBoot

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,'小二','123456'),
(2,'張三','123456'),
(3,'李四','123890')

新建項目

  1. 新建一個普通的maven項目

  2. 刪除src目錄

  3. 導入maven依賴

    
        <!--導入依賴-->
        <dependencies>
            <!--mysql驅動-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <!--mysql驅動-->
            <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、創建一個模塊

  • 編寫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&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </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 完全包含了面向數據庫執行 SQL 命令所需的所有方法。
        public static SqlSession  getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    
    }
    
    

2.3、編寫代碼

  • 實體類

    package com.kuang.pojo;
    
    //實體類
    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();
    }
    
  • 接口實現類由原來的UserDaoImpl轉變爲一個 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=綁定一個對應的Dao/Mapper接口-->
    <mapper namespace="com.kuang.dao.UserDao">
    
    <!--select查詢語句-->
    <!--id=綁定一個對應的Dao/Mapper接口方法-->
       <select id="getUserList" resultType="com.kuang.pojo.User">
           select * from mybatis.user
       </select>
    
    </mapper>
    

2.4、測試

注意點:

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

MapperRegistry是什麼?

核心配置文件中註冊 mappers

  • junit測試

    @Test
    public void test(){
        //第一步:獲得SqlSession對象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
    
        //方式一:getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
    
        for (User user : userList) {
            System.out.println(user);
        }
    
    
    
        //關閉SqlSession
        sqlSession.close();
    }
    
    

你們可以能會遇到的問題:

  1. 配置文件沒有註冊
  2. 綁定接口錯誤
  3. 方法名不對
  4. 返回類型不對
  5. Maven導出資源問題
	
        <!--    在build中配置resources,來防止我們資源導出失敗的問題-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/.*xml</include>
                </includes>
            </resource>
        </resources>
    </build>

3、CRUD

1、namespace

namespace中的包名要和 Dao/mapper 接口的包名一致

2、select

選擇,查詢語句;

  • id : 就是對應的namespace中的方法名
  • resultType:Sql語句執行的返回值
  • parameterType : 參數類型
  1. 編寫接口

    //根據ID查詢用戶
    User getUserById(int id);
    
  2. 編寫對應的mapper中的sql語句

    <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
            select * from mybatis.user where id = #{id}
    </select>
    
    
  3. 測試

        @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

    <!--對象中的屬性,可以直接取出來-->
    <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>

注意點:

  • 增刪改需要提交事務

6、分析錯誤

  • 標籤不要匹配錯
  • resource 綁定mapper,需要使用路徑
  • 程序配置文件必須符合規範
  • NullPointerException,沒有註冊到資源
  • 輸出的xml文件中存在中文亂碼問題
  • maven資源沒有導出問題

7、萬能Map

假設,我們的實體類,或者數據庫中的表,字段或者參數過多,我們應當考慮使用Map

    //萬能的Map
    int addUser2(Map<String,Object> map);


    <!--對象中的屬性,可以直接取出來    傳遞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傳遞參數,直接在sql中取出key即可 【parameterType=“map”】

對象傳遞參數,直接在sql中取對象的屬性即可【parameterType=“Object”】

只有一個基本類型參數的情況下,可以直接在sql中取到

多個參數用Map,或者註解**

8、思考題

模糊查詢怎麼寫?

  1. Java代碼執行的時候,傳遞通配符 % %

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

    select * from mybatis.user where name like "%"#{value}"%"
    

4、配置解析

1、核心配置文件

  • mybatis-config.xml

  • MyBatis 的配置文件包含了會深深影響 MyBatis 行爲的設置和屬性信息。

    configuration(配置)
    properties(屬性)
    settings(設置)
    typeAliases(類型別名)
    typeHandlers(類型處理器)
    objectFactory(對象工廠)
    plugins(插件)
    environments(環境配置)
    environment(環境變量)
    transactionManager(事務管理器)
    dataSource(數據源)
    databaseIdProvider(數據庫廠商標識)
    mappers(映射器)
    

2、環境配置(environments)

MyBatis 可以配置成適應多種環境

不過要記住:儘管可以配置多個環境,但每個 SqlSessionFactory 實例只能選擇一種環境。

學會使用配置多套運行環境

Mybatis默認的事務管理器就是 JDBC , 連接池 : POOLED

3、屬性(properties)

我們可以通過properties屬性來實現引用配置文件

這些屬性都是可外部配置且可動態替換的,既可以在典型的 Java 屬性文件中配置,亦可通過 properties 元素的子元素來傳遞。【db.properties】

配置需要按順序寫
在這裏插入圖片描述

編寫一個配置文件

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>

  • 可以直接引入外部文件
  • 可以在其中增加一些屬性配置
  • 如果兩個文件有同一個字段,優先使用外部配置文件的

4、類型別名(typeAliases)

  • 類型別名是爲 Java 類型設置一個短的名字
  • 存在的意義僅在於用來減少類完全限定名的冗餘
    <!--可以給實體類起別名-->
    <typeAliases>
        <typeAlias type="com.kuang.pojo.User" alias="User"/>
    </typeAliases>

也可以指定一個包名,MyBatis 會在包名下面搜索需要的 Java Bean,比如:

掃描實體類的包,它的默認別名就爲這個類的 類名,首字母小寫

<!--可以給實體類起別名-->
<typeAliases>
    <package name="com.kuang.pojo"/>
</typeAliases>

在實體類比較少的時候,使用第一種方式

如果實體類十分多,建議使用第二種

第一種可以DIY別名,第二種則不行,如果非要改,需要在實體上增加註解

@Alias("user")
public class User {}

5、設置

這是 MyBatis 中極爲重要的調整設置,它們會改變 MyBatis 的運行時行爲

在這裏插入圖片描述
在這裏插入圖片描述

6、其他配置

7、映射器(mappers)

MapperRegistry:註冊綁定我們的Mapper文件

方式一: 【推薦使用】

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

方式二:使用class文件綁定註冊

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

使用方式二注意點:

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

方式三:使用掃描包進行注入綁定

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

使用方式三注意點:

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

8、生命週期和作用域

在這裏插入圖片描述

生命週期和作用域,是至關重要的,因爲錯誤的使用會導致非常嚴重的併發問題

SqlSessionFactoryBuilder:

  • 一旦創建了 SqlSessionFactory,就不再需要它了
  • 局部變量

SqlSessionFactory:

  • 可以想象爲 :數據庫連接池
  • SqlSessionFactory 一旦被創建就應該在應用的運行期間一直存在,沒有任何理由丟棄它或重新創建另一個實例
  • 因此 SqlSessionFactory 的最佳作用域是應用作用域
  • 最簡單的就是使用單例模式或者靜態單例模式

SqlSession

  • 連接到連接池的一個請求
  • SqlSession 的實例不是線程安全的,因此是不能被共享的,所以它的最佳的作用域是請求或方法作用域。
  • 用完之後需要趕緊關閉,否則資源被佔用
    在這裏插入圖片描述

這裏面的每一個Mapper,就代表一個具體的業務

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

1、 問題

數據庫中的字段
在這裏插入圖片描述

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

@Date
public class User {
    
    private int id;
    private String name;
    private String password;
}
	/*
		你如果手動創建了有參的構造方法,
      	默認的無參方法就沒了,mybatis的返回值的封裝方式是先構造一個無參的對象,
      	然後通過set方法一個一個的往裏面set值
    */

測試出現問題

控制檯結果爲:User{id=1,name=‘鄭’,password=‘null’}

//    select * from mybatis.user where id = #{id}
//類型處理器
//    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

結果集映射

id   name   pwd
id   name   password
<!--結果集映射-->
<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.user where id = #{id}
</select>
  • resultMap 元素是 MyBatis 中最重要最強大的元素
  • ResultMap 的設計思想是,對於簡單的語句根本不需要配置顯式的結果映射,而對於複雜一點的語句只需要描述它們的關係就行了
  • ResultMap 最優秀的地方在於,雖然你已經對它相當瞭解了,但是根本就不需要顯式地用到他們
  • 如果世界總是這麼簡單就好了

6、日誌

6.1、日誌工廠

如果一個數據庫操作,出現了異常,我們需要排錯,日誌就是最好的助手

曾經:sout 、debug

現在:日誌工廠

在這裏插入圖片描述

  • SLF4J

  • LOG4J 【掌握】

  • 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組件
  • 我們也可以控制每一條日誌的輸出格式;
  • 通過定義每一條日誌信息的級別,我們能夠更加細緻地控制日誌的生成過程。
  • 通過一個配置文件來靈活地進行配置,而不需要修改應用的代碼。
  1. 先導入log4j的包

    <!-- https://mvnrepository.com/artifact/log4j/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
    
    #控制檯輸出的相關設置
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
    
    #文件輸出的相關設置
    log4j.appender.file = org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=./log/kuang.log
    log4j.appender.file.MaxFileSize=10mb
    log4j.appender.file.Threshold=DEBUG
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
    
    #日誌輸出級別
    log4j.logger.org.mybatis=DEBUG
    log4j.logger.java.sql=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.ResultSet=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    
  3. 配置log4j爲日誌的實現

    <settings>
        <setting name="logImpl" value="true"/>
    </settings>
    
  4. Log4j的使用!,直接測試運行剛纔的查詢

簡單使用

  1. 在要使用Log4j 的類中,導入包 import org.apache.log4j.Logger

  2. 日誌對象,參數爲當前類的class

    static Logger logger = Logger.getLogger(UserDaoTest.class);
    
  3. 日誌級別

    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 3;  #[0,n]

使用Mybatis實現分頁,核心SQL

  1. 接口

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

    <!--//分頁-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from  mybatis.user limit #{startIndex},#{pageSize}
    </select>
    
  3. 測試

    @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分頁

不再使用SQL實現分頁

  1. 接口

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

    <!--分頁2-->
    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from  mybatis.user
    </select>
    
  3. 測試

    @Test
    public void getUserByRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    
    //RowBounds實現
    RowBounds rowBounds = new RowBounds(1, 2);
    
    //通過Java代碼層面實現分頁
    List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
    
        for (User user : userList) {
        System.out.println(user);
        }
    
        sqlSession.close();
        }
    

7.3、分頁插件

在這裏插入圖片描述

瞭解即可

8、使用註解開發

8.1、面向接口編程

- 大家之前都學過面向對象編程,也學習過接口,但在真正的開發中,很多時候我們會選擇面向接口編程
- 根本原因 : 解耦 , 可拓展 , 提高複用 , 分層開發中 , 上層不用管具體的實現 , 大家都遵守共同的標準 , 使得開發變得容易 , 規範性更好
- 在一個面向對象的系統中,系統的各種功能是由許許多多的不同對象協作完成的。在這種情況下,各個對象內部是如何實現自己的,對系統設計人員來講就不那麼重要了
- 而各個對象之間的協作關係則成爲系統設計的關鍵。小到不同類之間的通信,大到各模塊之間的交互,在系統設計之初都是要着重考慮的,這也是系統設計的主要工作內容。面向接口編程就是指按照這種思想來編程

關於接口的理解

- 接口從更深層次的理解,應是定義(規範,約束)與實現(名實分離的原則)的分離
- 接口的本身反映了系統設計人員對系統的抽象理解
- 接口應有兩類:
- 第一類是對一個個體的抽象,它可對應爲一個抽象體(abstract class);
- 第二類是對一個個體某一方面的抽象,即形成一個抽象面(interface);
- 一個體有可能有多個抽象面。抽象體與抽象面是有區別的

三個面向區別

- 面向對象是指,我們考慮問題時,以對象爲單位,考慮它的屬性及方法
- 面向過程是指,我們考慮問題時,以一個具體的流程(事務過程)爲單位,考慮它的實現
- 接口設計與非接口設計是針對複用技術而言的,與面向對象(過程)不是一個問題.更多的體現就是 對系統整體的架構

8.2、使用註解開發

  1. 註解在接口上實現

    @Select("select * from user")
    List<User> getUsers();
    
  2. 需要在覈心配置文件中綁定接口!

    <!--綁定接口-->
    <mappers>
        <mapper class="com.kuang.dao.UserMapper"/>
    </mappers>
    
  3. 測試

本質:反射機制實現

底層:動態代理!
在這裏插入圖片描述

Mybatis詳細的執行流程!

在這裏插入圖片描述

8.3、CRUD

我們可以在工具類創建的時候實現自動提交事務

public static SqlSession  getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

編寫接口,增加註解

public interface UserMapper {

    @Select("select * from user")
    List<User> getUsers();

    // 方法存在多個參數,所有的參數前面必須加上 @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);
}

測試類

【注意:必須要講接口註冊綁定到我們的核心配置文件中】

關於@Param() 註解

  • 基本類型的參數或者String類型,需要加上
  • 引用類型不需要加
  • 如果只有一個基本類型的話,可以忽略,但是建議加上
  • 在SQL中引用的就是我們這裏的 @Param() 中設定的屬性名

#{}可以防止注入, 比${} 安全

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

使用步驟:

  1. 在IDEA中安裝Lombok插件

  2. 在項目中導入lombok的jar包

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>
    
  3. 在實體類上加註解

    @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

說明:

@Data:無參構造,get、set、tostring、hashcode,equals
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Getter

10、多對一處理

多對一:
在這裏插入圖片描述

  • 多個學生,對應一個老師
  • 對於學生這邊而言, 關聯, 多個學生,關聯一個老師 【多對一】
  • 對於老師而言, 集合 , 一個老師,有很多學生 【一對多】

在這裏插入圖片描述

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');

測試環境搭建

  1. 導入lombok
  2. 新建實體類 Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.XML文件
  5. 在覈心配置文件中綁定註冊我們的Mapper接口或者文件
  6. 測試查詢是否能夠成功

按照查詢嵌套處理

<!--
    思路:
        1. 查詢所有的學生信息
        2. 根據查詢出來的學生的tid,尋找對應的老師!  子查詢
    -->

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--複雜的屬性,我們需要單獨處理 對象: association 集合: collection -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{id}
</select>

按照結果嵌套處理

<!--按照結果嵌套處理-->
<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 多對一查詢方式:

  • 子查詢
  • 聯表查詢

11、一對多處理

比如:一個老師擁有多個學生

對於老師而言,就是一對多的關係

環境搭建

  1. 環境搭建,和剛纔一樣

實體類

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

按照結果嵌套處理


    <!--按結果嵌套查詢-->
    <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"/>
        <!--複雜的屬性,我們需要單獨處理 對象: association 集合: collection
        javaType="" 指定屬性的類型!
        集合中的泛型信息,我們使用ofType獲取
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

按照查詢嵌套處理

<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>

小結

  1. 關聯 - association 【多對一】
  2. 集合 - collection 【一對多】
  3. javaType & ofType
    1. JavaType 用來指定實體類中屬性的類型
    2. ofType 用來指定映射到List或者集合中的 pojo類型,泛型中的約束類型

注意點:

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

面試高頻

  • Mysql引擎
  • InnoDB底層原理
  • 索引
  • 索引優化!

12、動態 SQL

什麼是動態SQL:動態SQL就是指根據不同的條件生成不同的SQL語句

利用動態 SQL 這一特性可以徹底擺脫這種痛苦

動態 SQL 元素和 JSTL 或基於類似 XML 的文本處理器相似
在 MyBatis 之前的版本中,有很多元素需要花時間瞭解
MyBatis 3 大大精簡了元素種類,現在只需學習原來一半的元素便可
MyBatis 採用功能強大的基於 OGNL 的表達式來淘汰其它大部分元素

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=InnoDB DEFAULT CHARSET=utf8

創建一個基礎工程

  1. 導包

  2. 編寫配置文件

  3. 編寫實體類

    
    @Data
    public class Blog {
        private int id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
        
        
    }
    
  4. 編寫實體類對應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>

所謂的動態SQL,本質還是SQL語句 , 只是我們可以在SQL層面,去執行一個邏輯代碼

SQL片段

有的時候,我們可能會將一些功能的部分抽取出來,方便複用

  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="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>
    

注意事項:

  • 最好基於單表來定義SQL片段
  • 不要存在where標籤

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)

        我們現在傳遞一個萬能的map , 這map中可以存在一個集合!
-->
<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>

動態SQL就是在拼接SQL語句,我們只要保證SQL的正確性,按照SQL的格式,去排列組合就可以了

建議:

  • 現在Mysql中寫出完整的SQL,再對應的去修改成爲我們的動態SQL實現通用即可

13、緩存 (瞭解)

13.1、簡介

查詢  :  連接數據庫 ,耗資源!
	一次查詢的結果,給他暫存在一個可以直接取到的地方!--> 內存 : 緩存
	
我們再次查詢相同數據的時候,直接走緩存,就不用走數據庫了
  1. 什麼是緩存 [ Cache ]?

    • 存在內存中的臨時數據
    • 將用戶經常查詢的數據放在緩存(內存)中,用戶去查詢數據就不用從磁盤上(關係型數據庫數據文件)查詢,從緩存中查詢,從而提高查詢效率,解決了高併發系統的性能問題
  2. 爲什麼使用緩存?

    • 減少和數據庫的交互次數,減少系統開銷,提高系統效率
  3. 什麼樣的數據能使用緩存?

    • 經常查詢並且不經常改變的數據。【可以使用緩存】

13.2、Mybatis緩存

  • MyBatis包含一個非常強大的查詢緩存特性,它可以非常方便地定製和配置緩存。緩存可以極大的提升查詢效率
  • MyBatis系統中默認定義了兩級緩存:一級緩存二級緩存
    • 默認情況下,只有一級緩存開啓。(SqlSession級別的緩存,也稱爲本地緩存)

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

    • 爲了提高擴展性,MyBatis定義了緩存接口Cache。我們可以通過實現Cache接口來自定義二級緩存

13.3、一級緩存

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

測試步驟:

  1. 開啓日誌!
  2. 測試在一個Sesion中查詢兩次相同記錄
  3. 查看日誌輸出

緩存失效的情況:

  1. 查詢不同的東西

  2. 增刪改操作,可能會改變原來的數據,所以必定會刷新緩存!

  3. 查詢不同的Mapper.xml

  4. 手動清理緩存
    在這裏插入圖片描述

小結:一級緩存默認是開啓的,只在一次SqlSession中有效,也就是拿到連接到關閉連接這個區間段

一級緩存就是一個Map

13.4、二級緩存

  • 二級緩存也叫全局緩存,一級緩存作用域太低了,所以誕生了二級緩存
  • 基於namespace級別的緩存,一個名稱空間,對應一個二級緩存
  • 工作機制(就好像死後的遺產)
    • 一個會話查詢一條數據,這個數據就會被放在當前會話的一級緩存中
    • 如果當前會話關閉了,這個會話對應的一級緩存就沒了;但是我們想要的是,會話關閉了,一級緩存中的數據被保存到二級緩存中
    • 新的會話查詢信息,就可以從二級緩存中獲取內容
    • 不同的mapper查出的數據會放在自己對應的緩存(map)中

步驟:

  1. 開啓全局緩存

    <!--顯示的開啓全局緩存-->
    <setting name="cacheEnabled" value="true"/>
    
  2. 在要使用二級緩存的Mapper中開啓

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

    也可以自定義參數

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

    1. 出現問題:我們需要將實體類序列化,否則就會報錯

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

小結:

  • 只要開啓了二級緩存,在同一個Mapper下就有效
  • 所有的數據都會先放在一級緩存中
  • 只有當會話提交,或者關閉的時候,纔會提交到二級緩衝中

13.5、緩存原理

在這裏插入圖片描述

13.6、自定義緩存-ehcache

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

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

<!-- 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緩存實現!

<!--在當前Mapper.xml中使用二級緩存-->
<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"/>
    
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>
 
    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>
    <!--
       defaultCache:默認緩存策略,當ehcache找不到定義的緩存時,則使用這個緩存策略。只能定義一個。
     -->
    <!--
      name:緩存名稱。
      maxElementsInMemory:緩存最大數目
      maxElementsOnDisk:硬盤最大緩存個數。
      eternal:對象是否永久有效,一但設置了,timeout將不起作用。
      overflowToDisk:是否保存到磁盤,當系統當機時
      timeToIdleSeconds:設置對象在失效前的允許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。
      timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
      diskPersistent:是否緩存虛擬機重啓期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩衝區。
      diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
      memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)。
      clearOnFlush:內存數量最大時是否清除。
      memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)。
      FIFO,first in first out,這個是大家最熟的,先進先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。
      LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那麼現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。
   -->

</ehcache>

以後我們用Redis數據庫來做緩存K-V

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章