1. 程式人生 > >Spring Boot簡明教程之資料訪問(三):MyBatis

Spring Boot簡明教程之資料訪問(三):MyBatis

Spring Boot簡明教程之資料訪問(三):MyBatis

文章目錄

MyBatis簡介

MyBatis 是支援普通 SQL 查詢,儲存過程和高階對映的優秀持久層框架。MyBatis 消除 了幾乎所有的 JDBC 程式碼和引數的手工設定以及結果集的檢索。MyBatis 使用簡單的 XML 或註解用於配置和原始對映,將介面和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 物件)對映成資料庫中的記錄。對於MyBatis的更多介紹和基本使用可以檢視這篇文章:

Mybatis環境配置以及使用,在Spring Boot中有通過註解和使用XML配置兩種方式進行資料訪問,接下類我們將分別介紹這兩種方式:

使用註解進行資料訪問

專案建立

建立的過程和我們的第一篇文章:SpringBoot簡明教程之快速建立第一個SpringBoot應用大致相同,差別只是我們在挑選所需要的元件時,除了Web元件外,我們需要新增如下三個元件:MyBatis、MySQL、JDBC
在這裡插入圖片描述

或者在pox.xml檔案中,加入如下依賴:

<dependency>
	<groupId>org.springframework.boot</groupId
>
<artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>

我們在這次的依賴中發現了一個新的依賴:mybatis-spring-boot-starter,這個依賴並不是Spring Boot官方提供的,而是MyBatis提供的關於快速整合 Spring Boot 的一個元件包。這樣可以減少大量的配置。

專案目錄

在這裡插入圖片描述

建立資料庫檔案

organization.sql

CREATE TABLE `organization` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `active` smallint(1) NOT NULL,
  `company_name` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


建立Organization實體

public class Organization {
    private Integer id;
    private Integer active;
    private String companyName;
//省略Getter、Setter方法
}

編寫配置檔案application.yml

server:
  port: 9090

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useSSL=false
    username: root
    password:
    schema: classpath:sql/*.sql
    initialization-mode: always

編寫Mapper介面

public interface OrganizationMapper {

    @Select("SELECT * FROM organization where id = #{id}")
    Organization getOrganizationById (Integer id);

    @Delete("DELETE FROM organization where id = #{id}")
    int delOrganizationById (Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")  //使用自增主鍵
    @Insert("INSERT INTO organization(active,company_name) VALUES (#{active},#{companyName})")
    int insertOrganization(Organization organization);

}

編寫Controller

@RestController
public class OrganizationController {
    @Autowired
    OrganizationMapper organizationMapper;

    @GetMapping("/get/{id}")
    public Organization getOrganizationById (@PathVariable("id") Integer id){
        return  organizationMapper.getOrganizationById(id);
    }

    @GetMapping("/del/{id}")
    int delOrganizationById (@PathVariable("id") Integer id){
        return organizationMapper.delOrganizationById(id);
    }

    @GetMapping("/insert")
    Organization insertOrganization(Organization organization){
         organizationMapper.insertOrganization(organization);
         return organization;
    }
}

修改啟動類

@MapperScan(value = "com.example.springboot08.mapper")
@SpringBootApplication
public class Springboot08Application {
	public static void main(String[] args) {
		SpringApplication.run(Springboot08Application.class, args);
	}
}

資料訪問:

插入資料:

訪問:http://localhost:9090/insert?companyName=IBM&active=1

瀏覽器返回:{"id":1,"active":1,"companyName":"IBM"}

http://localhost:9090/insert?companyName=Oracle&active=0

瀏覽器返回:{"id":2,"active":0,"companyName":"Oracle"}

查詢

訪問:http://localhost:9090/get/2

瀏覽器返回:{"id":2,"active":0,"companyName":null}

這是我們發現剛剛成功插入的資料,現在查詢時companyName卻為null,這是為什麼呢?

因為我們在資料表中改欄位為company_name,而我們在實體類organization中卻為:companyName,所以我們在查詢的過程中,MyBatis無法進行對映,所以我們就需要去開啟駝峰命名規則:

更改配置檔案application.yml:

server:
  port: 9090
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useSSL=false
    username: root
    password:
    schema: classpath:sql/*.sql
    initialization-mode: never
mybatis:
  configuration:
    map-underscore-to-camel-case: true # 開啟駝峰命名

然後我們再次訪問:http://localhost:9090/get/2

瀏覽器返回:{"id":2,"active":0,"companyName":"Oracle"},我們就成功的進行了查詢。

刪除

訪問:http://localhost:9090/del/2

瀏覽器返回:1

使用XML配置進行資料訪問

專案目錄

在這裡插入圖片描述

Mapper介面編寫

public interface OrganizationMapper{

    Organization getOrganizationById (Integer id);

    int insertOrganization(Organization organization);

    int delOrganizationById (Integer id);
}

Mapper檔案編寫

OrganizationMapper.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.example.springboot08.mapper.OrganizationMapper">
    <select id="getOrganizationById" resultType="com.example.springboot08.bean.Organization">
        SELECT * FROM organization where id = #{id}
    </select>

    <insert id="insertOrganization" parameterType="com.example.springboot08.bean.Organization" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO organization(active,company_name) VALUES (#{active},#{companyName})
    </insert>
    <delete id="delOrganizationById" parameterType="Integer">
        DELETE FROM organization where id = #{id}
    </delete>
</mapper>

編寫配置檔案application.yml

server:
  port: 9090

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useSSL=false
    username: root
    password:
    schema: classpath:sql/*.sql
    initialization-mode: never
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations:
    - classpath:mapper/*.xml   # 指定Mapper目錄

資料訪問

插入資料

訪問:http://localhost:9090/insert?companyName=alibaba&active=1

瀏覽器返回:{"id":3,"active":1,"companyName":"alibaba"}

查詢

訪問:http://localhost:9090/get/1

瀏覽器返回:{"id":1,"active":1,"companyName":"IBM"}

刪除

訪問:http://localhost:9090/del/1

瀏覽器返回:1

總結

我們這裡介紹了有關Spring Boot整合MyBatis的使用,以及如何通過註解和XML配置的方式進行資料訪問。至於在具體採用哪種方式進行資料訪問,則根據專案的實際情況進行選擇即可。

原始碼地址

點這裡!!!

聯絡作者

有關轉載、錯誤指正、問題諮詢等事宜請掃碼關注個人公眾號進行聯絡,更有大量視訊學習資源分享