Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

申城異鄉人發表於2019-06-14

本系列部落格帶你一步一步的學習Spring Boot,如幫助到你,不勝榮幸,如有錯誤,歡迎指正!

本篇部落格我們講解下在Spring Boot中使用MyBatis訪問MySql資料庫(xml方式)的簡單用法。

本系列其它文章如下所示:

Spring Boot入門(一):使用IDEA建立Spring Boot專案並使用yaml配置檔案

Spring Boot入門(二):使用Profile實現多環境配置管理&如何獲取配置檔案值

Spring Boot入門(三):使用Scheduled註解實現定時任務

Spring Boot入門(四):開發Web Api介面常用註解總結

Spring Boot入門(五):使用JDBC訪問MySql資料庫

Spring Boot入門(六):使用MyBatis訪問MySql資料庫(註解方式)

1. 前期準備

假設你的機器已經安裝好了MySql,我們先執行如下語句建立資料庫和表:

CREATE DATABASE springbootaction_db;

create table author
(
  author_id   int auto_increment comment '作者id' primary key,
  author_name varchar(20) not null comment '姓名',
  pen_name    varchar(20) not null comment '筆名'
)
comment '作者';

2. 修改pom檔案

pom檔案引入mybatis的starter pom和mysql的驅動,因後面要編寫控制器,因此也引入下阿里巴巴的fastjson:

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

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.35</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

說明:引入了mybatis-spring-boot-starter後,可以不再引用spring-boot-starter-jdbc,因為前者已經依賴於後者。

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

3. 配置資料來源

在resources/application.yml中配置資料來源:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springbootaction_db
    username: root
    password:

4. 修改配置檔案

在application.yml中新增mybatis配置:

mybatis:
  mapper-locations: classpath:mybatis/*.xml
  type-aliases-package: com.zwwhnly.springbootaction.mybatis.entity

其中,mapper-locations為mybatis xml檔案的路徑,type-aliases-package為定義的實體所在的包名。

5. 定義資料庫實體

定義資料庫實體Author:

package com.zwwhnly.springbootaction.mybatis.entity;

import com.alibaba.fastjson.annotation.JSONField;

public class Author {
    @JSONField(name = "author_id")
    private Integer authorId;
    @JSONField(name = "author_name")
    private String authorName;
    @JSONField(name = "pen_name")
    private String penName;

    public Integer getAuthorId() {
        return authorId;
    }

    public void setAuthorId(Integer authorId) {
        this.authorId = authorId;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getPenName() {
        return penName;
    }

    public void setPenName(String penName) {
        this.penName = penName;
    }
}

6. 編寫Dao層程式碼

定義介面AuthorMapperV2:

package com.zwwhnly.springbootaction.mybatis.xml;

import com.zwwhnly.springbootaction.mybatis.entity.Author;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface AuthorMapperV2 {

    int add(@Param("author_name") String authorName, @Param("pen_name") String penName);

    int update(@Param("author_name") String authorName, @Param("pen_name") String penName, @Param("id") Integer id);

    int delete(Integer id);

    Author findAuthor(@Param("id") Integer id);

    List<Author> findAuthorList();
}

注意:介面要新增@Mapper註解。

7. 編寫Service層程式碼

定義類AuthorServiceV2:

package com.zwwhnly.springbootaction.mybatis.xml;

import com.zwwhnly.springbootaction.mybatis.entity.Author;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AuthorServiceV2 {
    @Autowired
    private AuthorMapperV2 authorMapperV2;

    public int add(String authorName, String penName) {
        return this.authorMapperV2.add(authorName, penName);
    }

    public int update(String authorName, String penName, Integer id) {
        return this.authorMapperV2.update(authorName, penName, id);
    }

    public int delete(Integer id) {
        return this.authorMapperV2.delete(id);
    }

    public Author findAuthor(Integer id) {
        return this.authorMapperV2.findAuthor(id);
    }

    public List<Author> findAuthorList() {
        return this.authorMapperV2.findAuthorList();
    }
}

注意:類新增@Service註解。

8. 新增mybatis xml檔案

在resources目錄下,新建mybatis資料夾,然後新建AuthorMapper.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.zwwhnly.springbootaction.mybatis.xml.AuthorMapperV2">
    <resultMap id="authorMap" type="Author">
        <result property="authorId" column="author_id"/>
        <result property="authorName" column="author_name"/>
        <result property="penName" column="pen_name"/>
    </resultMap>

    <insert id="add">
        INSERT INTO author(author_name, pen_name)
        VALUES(#{author_name}, #{pen_name});
    </insert>
    <update id="update">
        UPDATE author
        SET author_name = #{author_name,jdbcType=VARCHAR},
        pen_name = #{pen_name,jdbcType=VARCHAR}
        WHERE author_id = #{id,jdbcType=INTEGER};
    </update>
    <delete id="delete">
        DELETE FROM author
        WHERE author_id = #{id};
    </delete>
    <select id="findAuthor" resultMap="authorMap" resultType="Author">
       SELECT author_id, author_name, pen_name
       FROM author
       WHERE author_id = #{id};
    </select>
    <select id="findAuthorList" resultMap="authorMap">
        SELECT author_id, author_name, pen_name
        FROM author;
    </select>
</mapper>

9. 編寫Controller程式碼

新建控制器AuthorControllerV2:

package com.zwwhnly.springbootaction.controller;

import com.alibaba.fastjson.JSONObject;
import com.zwwhnly.springbootaction.mybatis.entity.Author;
import com.zwwhnly.springbootaction.mybatis.xml.AuthorServiceV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/mybatis/author")
public class AuthorControllerV2 {
    @Autowired
    private AuthorServiceV2 authorServiceV2;

    /**
     * 查詢作者列表
     */
    @RequestMapping(value = "getAuthorListV2", method = RequestMethod.GET)
    public Map<String, Object> getAuthorList() {
        List<Author> authorList = this.authorServiceV2.findAuthorList();
        Map<String, Object> param = new HashMap<>();
        param.put("total", authorList.size());
        param.put("rows", authorList);
        return param;
    }

    /**
     * 查詢單個作者資訊
     */
    @RequestMapping(value = "/getAuthorV2/{authorId:\\d+}", method = RequestMethod.GET)
    public Author getAuthor(@PathVariable Integer authorId) {
        Author author = this.authorServiceV2.findAuthor(authorId);
        if (author == null) {
            throw new RuntimeException("查詢錯誤");
        }
        return author;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "addV2", method = RequestMethod.POST)
    public void add(@RequestBody JSONObject jsonObject) {
        String authorName = jsonObject.getString("authorName");
        String penName = jsonObject.getString("penName");

        try {
            this.authorServiceV2.add(authorName, penName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("新增錯誤");
        }
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/updateV2/{authorId:\\d+}", method = RequestMethod.PUT)
    public void update(@PathVariable Integer authorId, @RequestBody JSONObject jsonObject) {
        Author author = this.authorServiceV2.findAuthor(authorId);
        String authorName = jsonObject.getString("authorName");
        String penName = jsonObject.getString("penName");

        try {
            this.authorServiceV2.update(authorName, penName, author.getAuthorId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("更新錯誤");
        }
    }

    /**
     * 刪除
     */
    @RequestMapping(value = "/deleteV2/{authorId:\\d+}", method = RequestMethod.DELETE)
    public void delete(@PathVariable Integer authorId) {
        try {
            this.authorServiceV2.delete(authorId);
        } catch (Exception e) {
            throw new RuntimeException("刪除錯誤");
        }
    }
}

10. 使用Postman驗證

10.1 驗證新增

因為新增是Post請求,因此這裡我們使用下Postman工具:

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

呼叫完介面,發現資料庫新增資料成功。

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

然後用同樣的方法新增下魯迅的資訊。

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

10.2 驗證更新

呼叫更新介面將魯迅的名字從周作人修改為周樹人:

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

呼叫完介面,發現資料庫更新資料成功。

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

10.3 驗證獲取列表

在瀏覽器訪問http://localhost:8080/mybatis/author/getAuthorListV2,返回資料如下:

{
  "total": 2,
  "rows": [
    {
      "authorId": 1,
      "authorName": "王衛國",
      "penName": "路遙"
    },
    {
      "authorId": 2,
      "authorName": "周樹人",
      "penName": "魯迅"
    }
  ]
}

10.4 驗證獲取單個資料

在瀏覽器訪問http://localhost:8080/mybatis/author/getAuthorV2/1,返回如下資料:

{
  "authorId": 1,
  "authorName": "王衛國",
  "penName": "路遙"
}

10.5 驗證刪除

呼叫刪除介面,將魯迅的資料刪除:

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

此時訪問http://localhost:8080/mybatis/author/getAuthorListV2,返回資料只有1條了:

{
  "total": 1,
  "rows": [
    {
      "authorId": 1,
      "authorName": "王衛國",
      "penName": "路遙"
    }
  ]
}

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

11. 原始碼

原始碼地址:https://github.com/zwwhnly/springboot-action.git,歡迎下載。

12. 參考

Spring Boot 揭祕與實戰(二) 資料儲存篇 - MyBatis整合

歡迎掃描下方二維碼關注個人公眾號:申城異鄉人。

Spring Boot入門(七):使用MyBatis訪問MySql資料庫(xml方式)

相關文章