1. 程式人生 > 其它 >4、SpringBoot整合之SpringBoot整合MyBatis

4、SpringBoot整合之SpringBoot整合MyBatis

SpringBoot整合Mybatis

一、建立SpringBoot專案

選擇Spring Web、JDBC API、MyBatis Framework、MySQL Driver




二、修改MySQL驅動版本、引入其他相關JAR包

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <!-- 修改JDBC版本 -->
    <version>5.1.47</version>
    <scope>runtime</scope>
</dependency>

<!-- 引入lombok -->
<!-- lombok能夠通過註解減少冗餘程式碼,比如實體類的get/set方法等 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

三、在MySQL中建庫、建表、插入資料

CREATE DATABASE db_springboot_test CHARSET='utf8';

USE db_springboot_test;

CREATE TABLE tab_student(
    pk_student_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '學生學號,起始值2021001',
    student_name VARCHAR(10) COMMENT '學生姓名',
    student_sex CHAR(1) COMMENT '學生性別',
    student_score DOUBLE(4,1) COMMENT '學生分數'
) COMMENT '學生表';

-- 執行一次,設定初始值
INSERT INTO tab_student VALUES(2021001,SUBSTR(MD5(RAND()),1,4),IF(RAND()>0.5,'男','女'),RAND()*100);

-- 可根據需要執行多次,隨機插入資料
INSERT INTO tab_student VALUES(NULL,SUBSTR(MD5(RAND()),1,4),IF(RAND()>0.5,'男','女'),RAND()*100);

SELECT * FROM tab_student;

四、在核心配置檔案application.properties中設定連線資料庫的四大引數以及相關配置

# 配置資料庫連線的四大引數
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://192.168.133.139:3306/db_springboot_test?useUnicode=true&characterEncoding=utf8&autoReconnect=true

spring.datasource.username=root

spring.datasource.password=root


# 指定sql對映檔案的位置
#mybatis.mapper-locations=classpath:mappers/*.xml


# 為實體類起別名
mybatis.type-aliases-package=cn.byuan.entity


# 顯示SQL語句
logging.level.cn.godfery.dao=debug

五、專案最終結構

六、建立實體類

package cn.byuan.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@NoArgsConstructor// 生成一個無參的構造方法
@AllArgsConstructor// 生成一個包含所有引數的構造方法
@Accessors(chain = true)// 生成方法的鏈式呼叫
@Data// 生成get/set方法、重寫toString方法等
public class Student implements Serializable {
    private Integer studentId;// 學生id
    private String studentName;// 學生姓名
    private String studentSex;// 學生性別
    private Double studentScore;// 學生分數
}

七、建立DAO層介面

package cn.byuan.dao;

import cn.byuan.entity.Student;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface StudentDao {

    @Insert("insert into tab_student values (null, #{studentName}, #{studentSex}, #{studentScore})")
    Integer addOneStudent(Student student);
    
    @Delete("delete from tab_student where pk_student_id=#{studentId}")
    Integer deleteOneStudentByStudentId(Integer studentId);

    @Update("update tab_student set student_name=#{studentName}, student_sex=#{studentSex}, student_score=#{studentScore} where pk_student_id=#{studentId}")
    Integer updateOneStudentByStudentId(Student student);

    @Select("select * from tab_student where pk_student_id=#{studentId}")
    // 通過註解配置Mapper對映檔案,使用該方式無需建立Mapper對映檔案
    // Mapper僅在查詢時使用,增、刪、改均不使用
    // 在增刪改上使用@Results會報錯
    @Results(id = "studentMapper", value = {
            @Result(id = true, property ="studentId", column ="pk_student_id", javaType = Integer.class),
            @Result(property ="studentName", column = "student_name", javaType = String.class),
            @Result(property ="studentSex", column = "student_sex", javaType = String.class),
            @Result(property ="studentScore", column = "student_score", javaType = Double.class)
    })
    Student getOneStudentByStudentId(Integer studentId);

    @Select("select * from tab_student")
    // 使用剛才建立的Mapper註解
    @ResultMap(value = {"studentMapper"})
    List<Student> getAllStudent();
}

八、在測試類中進行測試

package cn.byuan;

import cn.byuan.dao.StudentDao;
import cn.byuan.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class StudentDaoTests {

    @Autowired
    private StudentDao studentDao;

    @Test
    void addOneStudent(){
        Student student=new Student()
                .setStudentName("Echo")
                .setStudentSex("男")
                .setStudentScore(96.5);
        System.out.println(studentDao.addOneStudent(student));
    }

    @Test
    void deleteOneStudentByStudentId(){
        System.out.println(studentDao.deleteOneStudentByStudentId(2021005));
    }

    @Test
    void updateOneStudentByStudentId(){
        Student student=new Student()
                .setStudentId(2021001)
                .setStudentName("Echo")
                .setStudentSex("男")
                .setStudentScore(96.5);
        System.out.println(studentDao.updateOneStudentByStudentId(student));
    }

    @Test
    void getOneStudentByStudentIdTest() {
        System.out.println(studentDao.getOneStudentByStudentId(2021001));
    }

    @Test
    void getAllStudentTest(){
        List<Student> studentList=studentDao.getAllStudent();
        for(Student studentPart : studentList){
            System.out.println(studentPart);
        }
    }
}

測試結果:

原始碼地址:https://github.com/byuan98/springboot-integration/tree/master/test004_springboot_mybatis