1. 程式人生 > 其它 >SpringBoot整合整合MybatisPlus(測試)

SpringBoot整合整合MybatisPlus(測試)

整合MybatisPlus

簡介

MyBatis-Plus(簡稱 MP)是一個 MyBatis的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

官網

MyBatisPlus官網

建立專案工程

搭建環境並測試

系統要求

Java 8+

Maven 3.6.6 +

SpringBoot2.5+

引入 pom.xml 依賴

<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

編寫sql

-- 建立資料庫
create
database webapp1 charset utf8mb4;
-- 建立使用者名稱、密碼
create
user'webapp1'@'localhost'identified by'webapp1';
-- 授權
grant all
on webapp1.*to'webapp1'@'localhost';
-- 用使用者名稱、密碼登入
mysql -uwebapp1 -pwebapp1
-- 建立表
SET NAMES utf8mb4;
SET
FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
    `id`       int NOT NULL AUTO_INCREMENT,
    `username` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
    `sex`      varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
    `age`      int NULL DEFAULT NULL,
    `birthday` date NULL DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 554 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

配置application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3307/webapp1
    username: webapp1
    password: webapp1
    driver-class-name: com.mysql.cj.jdbc.Driver
    #mybatis日誌:新增後可以檢視執行的sql語句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

建立User類

package com.xiang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/21 2:50
 */

/**
 * `id`       int NOT NULL AUTO_INCREMENT,
 * `username` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
 * `sex`      varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
 * `age`      int NULL DEFAULT NULL,
 * `birthday` date NULL DEFAULT NULL,
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String username;
    private String sex;
    private int age;
    private Date birthday;
}

建立UserMapper介面

package com.xiang.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiang.pojo.User;
import org.springframework.stereotype.Component;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/21 13:04
 */
@Component ////該註解加不加都可以,主要是為了解決自動注入時的報紅問題
/**
 * 使用MybatisPlus不需要再建立mapper對應的xml檔案,只要繼承該介面並傳入相應的泛型即可
 */
public interface UserMapper extends BaseMapper<User> {
}

在啟動類新增掃描註解

package com.xiang;

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

@SpringBootApplication
@MapperScan("com.xiang.mapper")
//新增掃描註解,寫入mapper的路徑,否則會找不到介面並報錯
public class SpringBootMybatisPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatisPlusApplication.class, args);
    }

}

接下來進行測試

package com.xiang;

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

import javax.swing.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@SpringBootTest
class SpringBootMybatisPlusApplicationTests {
    @Autowired
    UserMapper userMapper;

    /**
     * 查所有
     */
    @Test
    void findAll() {
        List<User> list = userMapper.selectList(null);
        for (User user : list) {
            System.out.println(user);
        }
    }

    /**
     * 插入
     */
    @Test
    void insert() {
        User user = new User();
        user.setUsername("小五");
        user.setSex("女");
        int insert = userMapper.insert(user);
        if (insert > 0) {
            System.out.println("insert OK");
        } else {
            System.out.println("fail");
        }
    }

    /**
     * 更新
     */
    @Test
    void updateById() {
        try {
            SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
            Date date = format.parse("2000-1-1");
            userMapper.updateById(new User(608, "小小", "女", 20, date));

            User selectById = userMapper.selectById(606);
            System.out.println(selectById);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    /**
     * 刪除
     */
    @Test
    void  deleteById(){
        int byId = userMapper.deleteById(606);
        if (byId>0){
            System.out.println("deleteById  OK ");
        }else {
            System.out.println("fail");
        }
        List<User> list = userMapper.selectList(null);
        for (User user : list) {
            System.out.println(user);
        }
    }

}

控制檯執行結果

查所有
JDBC Connection [HikariProxyConnection@892262157 wrapping com.mysql.cj.jdbc.ConnectionImpl@70730db] will not be managed by Spring
==>  Preparing: SELECT id,username,sex,age,birthday FROM user
==> Parameters: 
<==    Columns: id, username, sex, age, birthday
<==        Row: 1, xiang, 男, 18, 2021-10-03
<==        Row: 559, 小向, 男, 18, 2021-10-04
<==        Row: 602, admin, 女, 18, 2021-10-20
<==        Row: 603, testbox, 女, 18, 2021-10-02
<==        Row: 604, 小一, 男, 18, 2021-10-16
<==        Row: 605, 小二, 女, 18, null
<==        Row: 607, 小四, 女, 21, null
<==        Row: 608, 小五, 女, 0, null
<==      Total: 8
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@b9a77c8]
插入
JDBC Connection [HikariProxyConnection@780570776 wrapping com.mysql.cj.jdbc.ConnectionImpl@37c36608] will not be managed by Spring
==>  Preparing: INSERT INTO user ( id, username, sex, age ) VALUES ( ?, ?, ?, ? )
==> Parameters: 0(Integer), 小五(String), 女(String), 0(Integer)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7a81065e]
insert OK
更新
JDBC Connection [HikariProxyConnection@117911771 wrapping com.mysql.cj.jdbc.ConnectionImpl@5793b87] will not be managed by Spring
==>  Preparing: UPDATE user SET username=?, sex=?, age=?, birthday=? WHERE id=?
==> Parameters: 小小(String), 女(String), 20(Integer), 1999-12-26 00:00:00.0(Timestamp), 608(Integer)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1645f294]
刪除
JDBC Connection [HikariProxyConnection@446093644 wrapping com.mysql.cj.jdbc.ConnectionImpl@2a869a16] will not be managed by Spring
==>  Preparing: DELETE FROM user WHERE id=?
==> Parameters: 608(Integer)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@75181b50]
deleteById  OK 

測試完結