SpringBoot整合MyBatis


一、准備工作

 

首先新建一個空工程,springboot相關的整合都放在該工程下。

 

 

 

 

該空工程名稱為spring-boot-example

 

 

 

創建好的空工程如下:

 

 

 

 

 

接着我們創建模塊

 

 

注:使用Spring Initializr是從Spring.io上獲取工程,需要保證電腦有網。 

 

 

模塊分組為com.spring.boot.example

模塊名為spring-boot-mybatis

 

 

 

 

添加MyBatis

 

 

 

添加MySQL驅動依賴 

 

 

 

 

整合mybatis只需要添加MyBatis Framework,SQL驅動即可,

但為了從前端到調用后端接口的完整流程,我們將Web中Spring Web也加上。

 

 

 

 

創建完成后如下圖所示

 

 

 

完整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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.spring.boot.example</groupId>
    <artifactId>spring-boot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-mybatis</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>

        <!-- web依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--  mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!-- MySQL驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

准備工作做完后,我們接下來創建一張表。和該表對應的實體類。

建表語句:

CREATE TABLE `user` (
  `id` int(11) NOT NULL COMMENT 'id',
  `name` varchar(50) DEFAULT NULL COMMENT 'name',
  `address` varchar(100) DEFAULT NULL COMMENT 'address',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

創建實體類

 

 

 

 

package com.spring.boot.example.springboot.mybatis.dao;

public class User {
    private Integer id;
    private String name;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

 

 

 

 

二、配置

  整體流程:

  1首先配置數據庫連接地址,用戶名密碼、驅動。

  2編寫對應xml文件並與接口關聯

  3 配置文件添加mybatis相關配置,Spring啟動類添加注解掃描對應接口

 

  2.1 配置數據庫基本信息

  

 

 

   在application.properties中進行配置,具體內容如下:

#數據庫地址,localhost使用的本地數據庫,如未配置localhost映射可使用127.0.0.1
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-example
#用戶名密碼
spring.datasource.username=xxxx
spring.datasource.password=xxxxxx
#數據庫驅動
#此處驅動有兩個
#com.mysql.jdbc.Driver
#com.mysql.cj.jdbc.Driver
#MySQL5用的驅動url是com.mysql.jdbc.Driver,MySQL6以后用的是com.mysql.cj.jdbc.Driver。
#使用何種驅動,根據安裝MySQL的版本而定
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#附:使用com.mysql.cj.jdbc.Driver如果出現時區問題(Caused by: java.sql.SQLException: The server time zone value 'XXXXXXXXX' is unrecognized...)
#解決方法一:可參閱https://blog.csdn.net/weixin_43976890/article/details/91397749(未嘗試)
#解決方法二:在數據庫中執行如下語句: set GLOBAL time_zone='+8:00';(已嘗試)


#以上配置都在org.springframework.boot.autoconfigure.jdbc包中。
#mybatis-spring-boot-starter依賴了spring-boot-starter-jdbc。
#自動配置時會將數據庫連接相關信息注入到mybatis中

 

數據庫連接信息配置后,我們先來測試下。

 

 

 在test文件下,找到測試類,SpringBootMyBatisApplicationTests.

測試類具體內容如下:

package com.spring.boot.example.springboot.mybatis;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@SpringBootTest
//使其運行在spring環境中進行測試.
//@RunWith如果沒有,需要添加Junit依賴,具體解決方法在下面。
@RunWith(SpringJUnit4ClassRunner.class)
class SpringBootMybatisApplicationTests {

    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
      //根據配置的數據庫信息獲取連接,執行語句 Connection connection
= dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select * from user");     //打印結果 while(resultSet.next()){ int id = resultSet.getInt(1); String name = resultSet.getString(2); String address = resultSet.getString(3); System.out.println("id:" + id + " name:" + name + " address:" + address); } } }

 

將光標放置contextLoads方法名上,鼠標右鍵點擊運行該方法。

 

控制台中打印了數據庫表中數據

 

 

 

沒有RunWith可將光標移至RunWith出,按住Alt+Enter點擊AddJUnit4 to classpath.

 

 

 

如果沒有提示,可直接在pom.xml中添加JUnit依賴,兩者效果一致。

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

 

 至此,數據庫信息配置正確。

  

  2.2編寫接口類xml文件。

  

 

 

 

   首先編寫接口類,具體內容如下:

package com.spring.boot.example.springboot.mybatis.mapper;

import com.spring.boot.example.springboot.mybatis.dao.User;

public interface UserMapper {

    User getUserById(Integer id);
}

 

 

  然后在resource文件夾下新建一個mapper文件夾編寫對應的xml

  

 

 

    具體內容如下:

<?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.spring.boot.example.springboot.mybatis.mapper.UserMapper">
    <!-- 此處與接口方法名對應 指定參數類型與返回結果類型-->
    <select id="getUserById" parameterType="java.lang.Integer" resultType="com.spring.boot.example.springboot.mybatis.dao.User">
        select * from user where id = #{id}
    </select>
</mapper>

  

    2.3配置文件添加相關信息,SpringBoot啟動類添加掃描接口注解

    

    在application.properties中添加如下配置,指明映射文件位置。

#指定映射xml文件位置
#classpath對應resource,*.xml表示配置mapper下所有xml文件
mybatis.mapper-locations=classpath:mapper/*.xml

    

    在SpringBoot啟動類下添加掃描接口的注解,這里掃描的是接口,不是xml。

    

package com.spring.boot.example.springboot.mybatis;

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

@SpringBootApplication
@MapperScan("com.spring.boot.example.springboot.mybatis.mapper")//掃描指定包下接口
public class SpringBootMybatisApplication {

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

}

    

    我們繼續在test下找到測試類,編寫測試UserMapper的方法

package com.spring.boot.example.springboot.mybatis;

import com.spring.boot.example.springboot.mybatis.dao.User;
import com.spring.boot.example.springboot.mybatis.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@SpringBootTest
//使其運行在spring環境中進行測試.
//@RunWith如果沒有,需要添加Junit依賴,解決方法參考下述
@RunWith(SpringJUnit4ClassRunner.class)
class SpringBootMybatisApplicationTests {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserMapper userMapper;

//    @Test
//    void contextLoads() throws SQLException {
//        Connection connection = dataSource.getConnection();
//        Statement statement = connection.createStatement();
//        ResultSet resultSet = statement.executeQuery("select * from user");
//
//        while(resultSet.next()){
//            int id = resultSet.getInt(1);
//            String name = resultSet.getString(2);
//            String address = resultSet.getString(3);
//            System.out.println("id:" + id + " name:" + name + " address:" + address);
//        }
//    }

    @Test void testUserMapper(){
        User userById = userMapper.getUserById(1);
        System.out.println(userById.getId() + " " + userById.getAddress() + " " + userById.getName());
    }

}

運行testUserMapper,控制台中輸出了查詢到的信息。

 

 

 

最后我們新建一個controller文件夾,創建一個UserController類。

 

 

package com.spring.boot.example.springboot.mybatis.controller;


import com.spring.boot.example.springboot.mybatis.dao.User;
import com.spring.boot.example.springboot.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ResponseBody
    @RequestMapping("/getUserById")
    public User getUserById(Integer id){
        return userMapper.getUserById(id);
    }
}

    

運行SpringBootDataApplication,

 

在地址欄輸入如下地址(或用127.0.0.1代替localhost)

 

 

 

 

參考:

https://blog.csdn.net/superdangbo/article/details/78732700

https://www.cnblogs.com/huang-changfan/p/10244855.html

https://www.bilibili.com/video/av38657363?p=59


免責聲明!

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



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