【狂神說JAVA】MyBatis筆記(所有代碼均經過測試)


所有代碼均經過測試

1、簡介

1.1 什么是Mybatis

在這里插入圖片描述

  • MyBatis 是一款優秀的持久層框架;
  • 它支持自定義 SQL、存儲過程以及高級映射。MyBatis 免除了幾乎所有的 JDBC 代碼以及設置參數和獲取結果集的工作。MyBatis 可以通過簡單的 XML 或注解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)為數據庫中的記錄。

1.2 持久化

數據持久化

  • 持久化就是將程序的數據在持久狀態和瞬時狀態轉化的過程
  • 內存:斷電即失
  • 數據庫(Jdbc),io文件持久化。

為什么要持久化?

  • 有一些對象,不能讓他丟掉
  • 內存太貴

1.3 持久層

Dao層、Service層、Controller層

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

1.4 為什么需要MyBatis

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

2、第一個Mybatis程序

思路:搭建環境 --> 導入MyBatis --> 編寫代碼 --> 測試

2.1 搭建環境

新建項目

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

  2. 刪除src目錄 (就可以把此工程當做父工程了,然后創建子工程)

  3. 導入maven依賴

    <!--導入依賴-->
    <dependencies>
        <!--mysqlq驅動-->
        <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.4</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
  4. 創建一個Module

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?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

編寫mybatis工具類

public class MybatisUtils {
    static SqlSessionFactory sqlSessionFactory = null;
    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(){
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //return  sqlSession;
        return sqlSessionFactory.openSession();
    }
}

2.3測試

2.3.1注意點

錯誤:org.apache.ibatis.binding.BindingException: Type interface com.Sun.Dao.UserDao is not known to the MapperRegistry.

< !--每一個Mapper.xml都需要Mybatis核心配置文件中注冊!-->

<mappers>
    <mapper resource="com/Sun/Dao/UserMapper.xml"></mapper>
</mappers>

2.3.2約定大於配置

<!--在build中配置resources,來防止我們資源導出失敗的問題-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

能會遇到的問題:

  1. 配置文件沒有注冊
  2. 綁定接口錯誤
  3. 方法名不對
  4. 返回類型不對
  5. Maven導出資源問題

3、CURD

3.1、namespace

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

3.2. select

選擇,查詢語句;

  • id:就是對應的namespace中的方法名;

  • resultType : Sql語句執行的返回值;

  • parameterType : 參數類型;

    編寫接口

public interface UserMapper {
    List<User> getAllUser();
    User getUserByID(int id);
}

編寫對應的mapper中的sql語句

<select id="getAllUser" resultType="com.Sun.pojo.User">
    select * from mybatis.user
</select>

測試

@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int number = mapper.addUser(new User(6, "小明", "234567"));
    if(number>0){
        System.out.println("插入成功");
    }
    sqlSession.commit();
    sqlSession.close();
}

3.3.注意:增刪改查一定要提交事務:

sqlSession.commit();

3.4. Insert

<insert id="addUser"  parameterType="com.Sun.pojo.User">
    insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd});
</insert>

3.5. update

<update id="updateUser" parameterType="com.Sun.pojo.User">
    update mybatis.user set  name=#{name},pwd=#{pwd}  where id=#{id} ;
</update>

3.6. Delete

<delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id=#{id}
</delete>

3.7.分析錯誤

標簽不要匹配錯

resource綁定mapper,需要使用路徑!

程序配置文件必須符合規范!

NullPointerException,沒有注冊到資源!

輸出的xml文件中存在中文亂碼問題!

maven資源沒有導出問題!

3.8.萬能Map

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

UserMapper接口

int addUser2(Map<String,Object>map);

UserMapper.xml

<insert id="addUser2"  parameterType="com.Sun.pojo.User">
    insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{userpassword})
</insert>

測試

@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Object> map = new HashMap<>();
    map.put("userid",7);
    map.put("username","小李");
    map.put("userpassword","12345678");
    int number = mapper.addUser2(map);
    if(number>0){
        System.out.println("插入成功");
    }
    sqlSession.commit();
    sqlSession.close();
}

Map傳遞參數,直接在sql中取出key即可! 【parameter=“map”】

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

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

多個參數用Map , 或者注解!

3.9.模糊查詢

模糊查詢這么寫?

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

    List<User> userByName = mapper.getUserByName("%程%");
    
  2. 在sql拼接中使用通配符

    <select id="getUserByName" resultType="com.Sun.pojo.User">
        select *from mybatis.user where name like "%"#{value}"%";
    </select>
    

4、配置解析

4.1. 核心配置文件

  • mybatis-config.xml

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

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

4.2. 環境配置 environments

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

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

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

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

4.3. 屬性 properties

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

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

編寫一個配置文件 db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=ture&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username=root
password=123456

在核心配置文件中引入

<properties resource="db.properties">
    <property name="username" value="root"/>
    <property name="password" value="cgj532416"/>
</properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些屬性配置
  • 如果兩個文件有同一個字段,優先使用外部配置文件的

4.4. 類型別名 typeAliases

  • 類型別名可為 Java 類型設置一個縮寫名字。 它僅用於 XML 配置.
  • 意在降低冗余的全限定類名書寫。
<!--可以給實體類起別名-->
<typeAliases>
    <typeAlias type="com.Sun.pojo.User" alias="User"/>
</typeAliases>

​ 也可以指定一個包,每一個在包 com.Sun.pojo 中的 Java Bean,在沒有注解的情況下,會使用 Bean 的首字母小寫的非限定類名來作為它的別名。 比如com.Sun.pojo.User 的別名為 user,;若有注解,則別名為其注解值。見下面的例子:

<typeAliases>
    <package name="com.Sun.pojo"/>
</typeAliases>
//注解修改別名
@Alias("user")
public class User {}

注意:

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

如果實體類十分多,建議用第二種掃描包的方式。

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

4.5. 設置 Settings

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

img

4.6. 其他配置

4.7. 映射器 mappers

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

方式一:【推薦使用】

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

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

<mappers>
    <mapper class="com.Sun.Dao.UserMapper"></mapper>
</mappers>

注意點:

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

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

<mappers>
    <package name="com.Sun.Dao"/>
</mappers>

注意點:

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

4.8. 作用域和生命周期

image-20201130171031147

聲明周期和作用域是至關重要的,因為錯誤的使用會導致非常嚴重的並發問題

SqlSessionFactoryBuilder:

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

SqlSessionFactory:

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

SqlSession:

  • 連接到連接池的一個請求
  • SqlSession 的實例不是線程安全的,因此是不能被共享的,所以它的最佳的作用域是請求或方法作用域。
  • 用完之后需要趕緊關閉,否則資源被占用!

image-20201130171113192

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

5.1. 問題

數據庫中的字段

image-20201130202724164

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

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

測試出現問題

image-20201130202839787

// select * from user where id = #{id}
// 類型處理器
// select id,name,pwd from user where id = #{id}

解決方法:

  • 起別名
<select id="getUserByID" resultType="com.Sun.pojo.User" parameterType="int">
    select id,name,pwd as password from mybatis.user where id = #{id}
</select>

5.2. resultMap

結果集映射

id name pwd

id name password

<!--結果集映射-->
<resultMap id="UserMap" type="User">
    <!--column數據庫中的字段,property實體類中的屬性-->
    <result column="id" property="id"></result>
    <result column="name" property="name"></result>
    <result column="pwd" property="password"></result>
</resultMap>

<select id="getUserByID" resultMap="UserMap" parameterType="int">
    select * from mybatis.user where id = #{id}
</select>

  • resultMap 元素是 MyBatis 中最重要最強大的元素。
  • ResultMap 的設計思想是,對簡單的語句做到零配置,對於復雜一點的語句,只需要描述語句之間的關系就行了。
  • ResultMap 的優秀之處——你完全可以不用顯式地配置它們。
  • 如果這個世界總是這么簡單就好了。

6、日志

6.1 日志工廠

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

曾經:sout、debug

現在:日志工廠

img

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

在MyBatis中具體使用哪一個日志實現,在設置中設定

STDOUT_LOGGING

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

image-20201201115045268

6.2 Log4j

什么是Log4j?

  • Log4j是Apache的一個開源項目,通過使用Log4j,我們可以控制日志信息輸送的目的地是控制台、文件、GUI組件;
  • 我們也可以控制每一條日志的輸出格式;
  • 通過定義每一條日志信息的級別,我們能夠更加細致地控制日志的生成過程;
  • 最令人感興趣的就是,這些可以通過一個配置文件來靈活地進行配置,而不需要修改應用的代碼。
  1. 先導入log4j的包
<dependencies>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>
  1. 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/SUN.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

  1. 配置settings為log4j實現
<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>
  1. 測試運行

image-20201201141754951

image-20201201141812987

Log4j簡單使用

  1. 在要使用Log4j的類中,導入包 import org.apache.log4j.Logger;
  2. 日志對象,參數為當前類的class對象
  3. 日志級別
logger.info("info: 測試log4j");
logger.debug("debug: 測試log4j");
logger.error("error:測試log4j");
  1. info
  2. debug
  3. error

7、分頁

思考:為什么分頁?

  • 減少數據的處理量

7.1 使用Limit分頁

SELECT * from user limit startIndex,pageSize 

使用MyBatis實現分頁,核心SQL

  1. 接口
List<User>  getUserByLimit(Map<String,Integer> map);
  1. Mapper.xml
<!--分頁查詢-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
    select * from user limit #{startIndex},#{pageSize}
</select>
  1. 測試
@Test
public void test3(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Integer> map = new HashMap<>();
    map.put("startIndex",2);
    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. 接口
List<User> getUserByRowBounds();
  1. mapper.xml
    <select id="getUserByRowBounds" resultType="User" >
        select * from mybatis.user
    </select>
  1. 測試
public void getUserByRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //RowBounds實現
    RowBounds rowBounds = new RowBounds(1, 2);
    //通過Java代碼層面實現分頁
    List<User> userList = sqlSession.selectList("com.Sun.Dao.UserMapper.getUserByRowBounds", null, rowBounds);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

7.3 分頁插件

image-20201201145829063

8、使用注解開發

8.1 面向接口開發

三個面向區別

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

8.2 使用注解開發

  1. 注解在接口上實現
@Select("select * from mybatis.user")
List<User> getAllUser();
  1. 需要在核心配置文件中綁定接口
<mappers>
    <mapper class="com.Sun.Dao.UserMapper"></mapper>
</mappers>
  1. 測試

本質:反射機制實現

底層:動態代理

8.3MyBatis詳細執行流程

image-20201202162748162

8.4 注解CURD

public interface UserMapper {
   //方法存在多個參數,所有的參數前面必須加上@Param("id")注解
    @Select("select * from mybatis.user")
    List<User> getAllUser();

    @Select("select * from mybatis.user where id= #{id}")
    User getUserByID(@Param("id") int id);

    @Update("update user set name=#{name},pwd=#{password}where id= #{id}")
    int updateUser(User user);

    @Insert("insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{password})")
    int addUser(User user);

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);
}

關於@Param( )注解

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

#{} 和 ${}

9、Lombok

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

使用步驟:

  1. 在IDEA中安裝Lombok插件
  2. 在項目中導入lombok的jar包
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
    <scope>provided</scope>
</dependency>
  1. 在程序上加注解
@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
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;
}

image-20201202172443670

10、多對一處理

多對一:

多個學生,對應一個老師
對於學生這邊而言,關聯...多個學生,關聯一個老師【多對一】
對於老師而言,集合,一個老師又很多學生【一對多】
USER nybatis
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);

10.1. 測試環境搭建

  1. 導入lombok
  2. 新建實體類Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中綁定注冊我們的Mapper接口或者文件 【方式很多,隨心選】
  6. 測試查詢是否能夠成功

10.2. 按照查詢嵌套處理

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

10.3. 按照結果嵌套處理

<resultMap id="studentTeacher2" type="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" column="tid">
        <result property="name" column="tname"></result>
    </association>
</resultMap>
<select id="getStudent2" resultMap="studentTeacher2">
    select s.id sid,s.name sname,t.name tname 
    from mybatis.teacher t,mybatis.student  s 
    where s.tid=t.id
</select>

回顧Mysql多對一查詢方式:

  • 子查詢 (按照查詢嵌套)
  • 聯表查詢 (按照結果嵌套)

11、一對多處理

一個老師多個學生;

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

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

11.2. 按照結果嵌套嵌套處理

<select id="getTeacher" resultMap="studentTeacher">
    select t.id tid,t.name tname, s.id sid,s.name sname 
    from mybatis.teacher t,mybatis.student s 
    where s.tid=t.id and t.id=#{tid};
</select>

<resultMap id="studentTeacher" type="teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

11.3.按照查詢嵌套處理

<select id="getTeacher2" resultMap="studentTeacher2">
    select * from mybatis.teacher where id=#{tid};
</select>
<resultMap id="studentTeacher2" type="teacher">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="students" ofType="com.Sun.pojo.Student" javaType="ArrayList" select="getStudentByid" column="id"/>
</resultMap>
<select id="getStudentByid" resultType="student">
    select *from mybatis.student where tid=#{id}
</select>

11.4.小結

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

注意點:

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

11.5.面試高頻

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

12、動態SQL

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

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


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

12.1.搭建環境

CREATE TABLE `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 NOT NULL COMMENT '創建時間',
  `views` INT(30) NOT NULL COMMENT '瀏覽量',
  PRIMARY KEY (`id`)
)

創建一個基礎工程

  1. 導包
  2. 編寫配置文件
  3. 編寫實體類
@Data
public class Blog {
    private int id;
    private String title;
    private String author;
    private Date createTime;// 屬性名和字段名不一致
    private int views;
}

  1. 編寫實體類對應Mapper接口和Mapper.xml文件

  2. 駝峰命名

<setting name="mapUnderscoreToCamelCase" value="true"/>

12.2.IF

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

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

12.4.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層面,去執行一個邏輯代碼

if

where , set , choose ,when

12.5.SQL片段

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

  1. 使用SQL標簽抽取公共的部分
<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>
  1. 在需要使用的地方使用Include標簽引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <include refid="if-title-author"/>
    </where>
</select>

注意事項:

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

12.6.Foreach

image-20201203210615847

<!--
  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. 查看日志輸出

image-20201203214833012

緩存失效的情況:

  1. 查詢不同的東西
  2. 增刪改操作,可能會改變原來的數據,所以必定會刷新緩存!

image-20201203215137626

  1. 查詢不同的Mapper.xml

  2. 手動清理緩存!

image-20201203215222593

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

一級緩存就是一個Map。

13.4、二級緩存

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

步驟:

  1. 開啟全局緩存
<!--顯示的開啟全局緩存-->
<setting name="cacheEnabled" value="true"/>
  1. 在要使用二級緩存的Mapper中開啟
<!--在當前Mapper.xml中使用二級緩存-->
<cache/>
  1. 也可以自定義參數
<!--在當前Mapper.xml中使用二級緩存-->
<cache  eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"/>
  1. 測試

  2. 問題:我們需要將實體類序列化!否則就會報錯!

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

小結:

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

13.5、緩存原理

image-20201204095725019

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

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

Redis數據庫來做緩存! K-V

14.練習:29道練習題實戰!點這里


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM