天天看點

2021-08-23 SpringBoot 整合Mybatis MybatisPlus學習1.1跳過測試類打包1.2建立項目。 編輯測試類 Bug 2. MybatisPlus學習關鍵在于繼承特定的接口分析問題: 對象如何轉化為Sql.

1.1跳過測試類打包

需求說明:maven執行打包指令時,預設條件下會執行測試類中的方法,測試方法中一旦報錯,則install的操作執行失敗。

解決方案: 要求install時 不要執行test方法。

解決方案:跳過測試類打包

   <properties>

        <!--指定JDK版本-->

        <java.version>1.8</java.version>

        <!--跳過測試類打包-->

        <skipTests>true</skipTests>

    </properties>

1.2建立項目。

對demo_user資料進行增删改查

1建立maven工程

2.導入pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jt</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <!--Springboot的啟動器 在内部已經将整合的配置寫好,實作拿來就用-->
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <!--支援熱部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!--引入插件lombok 自動的set/get/構造方法插件  -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.5.3</version>
        </dependency>


    </dependencies>

</project>
           

編輯主啟動類

Spring管理Mapper接口(方式一)

說明: @Mapper注解 一般辨別接口中. 如果有多個接口,則應該辨別多次.

優化: 可以采用 @MapperScan(“xxxx”)進行優化.

2021-08-23 SpringBoot 整合Mybatis MybatisPlus學習1.1跳過測試類打包1.2建立項目。 編輯測試類 Bug 2. MybatisPlus學習關鍵在于繼承特定的接口分析問題: 對象如何轉化為Sql.

Spring管理Mapper接口(方式二)

package com.jt;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.jt.dao")
public class Runapp {
    public static void main(String[] args) {
        SpringApplication.run(Runapp.class, args);
    }
}
      

資料庫

2021-08-23 SpringBoot 整合Mybatis MybatisPlus學習1.1跳過測試類打包1.2建立項目。 編輯測試類 Bug 2. MybatisPlus學習關鍵在于繼承特定的接口分析問題: 對象如何轉化為Sql.

 1.4 整合mybatis

//序列化接口的作用:保證對象網絡傳輸的有效性

package com.jt.pojo;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Data
@Accessors(chain = true)
public class User implements Serializable {
 private Integer id;
 private String name;
 private Integer age;
 private String sex;
}
      

1.4.2 編輯YML檔案

編輯 1.資料源 2.整合mybatis

#端口配置
server:
  port: 8080

#配置資料源
spring:
  datasource:
    #如果使用高版本驅動 則添加cj
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/jt?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root

#Spring整合Mybatis
mybatis:
  #定義别名包
  type-aliases-package: com.jt.pojo
  #導入映射檔案
  mapper-locations: classpath:/mappers/*.xml
  #開啟駝峰映射
  configuration:
    map-underscore-to-camel-case: true
      
  • 資料庫配置參數:
  • 1.serverTimezone=GMT%2B8& 時區
  • 2.useUnicode=true& 是否使用unicode編碼
  • 3.characterEncoding=utf8& 字元集使用utf-8
  • 4.autoReconnect=true& 自動重連
  • 5.allowMultiQueries=true 運作批量操作

1.4.3 編輯映射檔案

<?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">
<mapper namespace="com.jt.dao.UserMapper">
   <!--查詢全表-->
    <select id="getlist" resultType="User">
        select * from demo_user
    </select>
<!--按照id删除-->
    <delete id="delete">
        delete from demo_user where id=#{id}
    </delete>
    <!--增加記錄-->
    <insert id="insert">
        insert into demo_user values (#{id},#{name},#{age},#{sex})
    </insert>

    <!--修改-->
    <update id="update">
        update demo_user set name=#{newname} where id=#{id}
    </update>
</mapper>      

 編輯測試類

package com.jt.test;

import com.jt.dao.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class Test {
    @Autowired
    private UserMapper userMapper;
    @org.junit.jupiter.api.Test
    public void test(){
        List<User> getlist = userMapper.getlist();
        System.out.println(getlist);
       //删除
        userMapper.delete(233);
        //增加
        User user = new User().setId(null).setName("HANY").setAge(156).setSex("女");
        userMapper.insert(user);
        //更新
        userMapper.update(234, "eafhf");
    }

}
      

 Bug

說明: 通過包掃描的路徑,在運作期間實作對象的建立. 實作了資料的綁定.是以下邊的紅線屬于誤報…

解決方案

2021-08-23 SpringBoot 整合Mybatis MybatisPlus學習1.1跳過測試類打包1.2建立項目。 編輯測試類 Bug 2. MybatisPlus學習關鍵在于繼承特定的接口分析問題: 對象如何轉化為Sql.

 說明: 如果xml的映射檔案,則根目錄下(不建議), 則加載時采用classpath*😕*.xml的結構.

強制加載根目錄下的所有的xml檔案.

放在檔案夾下

2021-08-23 SpringBoot 整合Mybatis MybatisPlus學習1.1跳過測試類打包1.2建立項目。 編輯測試類 Bug 2. MybatisPlus學習關鍵在于繼承特定的接口分析問題: 對象如何轉化為Sql.

 2. MybatisPlus學習

ORM思想,對象關系映射(object Relational Mapping),是一種程式設計技術,用于實作面向對象程式設計語言裡不同類型系統的資料之間的轉換

面向對象的方式來操作資料庫!

以對象的方式實作資料庫CRUD操作

要求通過某種機制将對象動态的轉換為sql,之後實作資料庫的操作,可以不寫sql語句

2.2 Mybatis優點/缺點

優點:

1.Mybatis 内部整合了JDBC, 簡化了持久層開發.

2.Mybatis可以自動的封裝結果集的對象 滿足ORM中的一個條件.是以将Mybatis稱之為半自動化的ORM映射架構.

3.Mybatis有緩存機制 一級緩存/二級緩存.提高使用者得查詢效率.

4.Mybatis支援多種類型的資料庫. 整合簡單.

缺點:

1.實作資料的封裝 resultMap 封裝複雜!!!

2.針對于單表的CRUD的操作 不夠便捷. Sql都需要手寫!!!

3.個别的情況下二級緩存配置不生效!!!

2.4 MP入門案例(資料庫表同上)

第一,導入jar包更換原有mybatis

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>      

2.4.2 實作映射

2021-08-23 SpringBoot 整合Mybatis MybatisPlus學習1.1跳過測試類打包1.2建立項目。 編輯測試類 Bug 2. MybatisPlus學習關鍵在于繼承特定的接口分析問題: 對象如何轉化為Sql.

關鍵在于繼承特定的接口

關鍵詞: 封裝—多态—繼承

說明: MP在内部準備一個BaseMapper的接口 BaseMapper内部幾乎将單表的CURD操作 都進行了編輯. 使用者自己的Mapper接口可以繼承即可.

package com.jt.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jt.pojo.User;

import java.util.List;

//@Mapper将該接口交給Spring管理
public interface UserMapper extends BaseMapper<User> {
    List<User> get();
}
      

第三步 yml檔案中mybatis改成

mybatis-plus:      

最後可以進行測試:!!!

package com.jt.test;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TestMP {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void test01(){
       //增加
        User user = new User();
        user.setName("阿富汗").setAge(40).setSex("厲害");
        userMapper.insert(user);
       //查詢
        User user1 = userMapper.selectById(21);
        System.out.println(user1);
    }
}
      

分析問題: 對象如何轉化為Sql.

核心理論

.例子: userMapper.insert(user);

dogMapper.insert(dog);

關鍵在轉化

Sql:

1. insert into 表名(字段名稱…) value (屬性的值…)

總結: MP将正常的操作進行抽取, 采用公共的接口進行定義. 之後隻需要按照使用者的參數, 動态的拼接Sql即可.

重點: 對java反射機制 有一定的了解

  1. userMapper.insert(user);
    使用者傳入user對象,通過對象.getclass()擷取類型      
  2. 根據class的類型,通過反射動态擷取指定的注解@TableName("demo_user"),得到表tableName.value();      
  3. 根據class的類型,知道其屬性,由屬性名稱擷取注解,擷取到表字段的名稱@TableField(“name”),
  4. 最終拼接出完整的sql語句
  5. 最終将Sql 由MP交給Mybatis執行sql. 最終實作資料的入庫操作.