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

本系列博客記錄本身學習Spring Boot的歷程,如幫助到你,不勝榮幸,若有錯誤,歡迎指正!java

本篇博客咱們講解下在Spring Boot中使用MyBatis訪問MySql數據庫的簡單用法。mysql

1.前期準備

假設你的機器已經安裝好了MySql,咱們先執行以下語句建立數據庫和表:git

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:github

<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,由於前者已經依賴於後者。web

3.配置數據源

在resources/application.yml中配置數據源:spring

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

4.定義數據庫實體

定義數據庫實體Author:sql

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;
    }
}
複製代碼

5.編寫Dao層代碼

定義接口AuthorMapper:數據庫

package com.zwwhnly.springbootaction.mybatis.annotation;

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

import java.util.List;

@Mapper
public interface AuthorMapper {
    @Insert("insert into author(author_name, pen_name) values(#{author_name}, #{pen_name})")
    int add(@Param("author_name") String authorName, @Param("pen_name") String penName);

    @Update("update author set author_name = #{author_name}, pen_name = #{pen_name} where author_id = #{id}")
    int update(@Param("author_name") String authorName, @Param("pen_name") String penName, @Param("id") Integer id);

    @Delete("delete from author where author_id = #{id}")
    int delete(Integer id);

    @Select("select author_id as authorId, author_name as authorName, pen_name as penName from author where author_id = #{id}")
    Author findAuthor(@Param("id") Integer id);

    @Select("select author_id as authorId, author_name as authorName, pen_name as penName from author")
    List<Author> findAuthorList();
}
複製代碼

注意:接口要添加@Mapper註解。apache

6.編寫Service層代碼

定義類AuthorService:json

package com.zwwhnly.springbootaction.mybatis.annotation;

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 AuthorService {
    @Autowired
    private AuthorMapper authorMapper;

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

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

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

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

    public List<Author> findAuthorList() {
        return this.authorMapper.findAuthorList();
    }
}
複製代碼

注意:類添加@Service註解。

7.編寫Controller代碼

新建控制器AuthorController:

package com.zwwhnly.springbootaction.controller;

import com.alibaba.fastjson.JSONObject;
import com.zwwhnly.springbootaction.mybatis.entity.Author;
import com.zwwhnly.springbootaction.mybatis.annotation.AuthorService;
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 AuthorController {
    @Autowired
    private AuthorService authorService;

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

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

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

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

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

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

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

8.使用Postman驗證

8.1驗證新增

由於新增是Post請求,所以這裏咱們使用下Postman工具:

調用完接口,發現數據庫新增數據成功。

而後用一樣的方法新增下魯迅的信息。

8.2驗證更新

調用更新接口將魯迅的名字從周做人修改成周樹人:

調用完接口,發現數據庫更新數據成功。

8.3驗證獲取列表

在瀏覽器訪問http://localhost:8080/mybatis/author/getAuthorList,返回數據以下:

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

8.4驗證獲取單個數據

在瀏覽器訪問http://localhost:8080/mybatis/author/getAuthor/1,返回以下數據:

{
  "authorId": 1,
  "authorName": "王衛國",
  "penName": "路遙"
}
複製代碼

8.5驗證刪除

調用刪除接口,將魯迅的數據刪除:

此時訪問http://localhost:8080/mybatis/author/getAuthorList,返回數據只有1條了:

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

9.源碼

源碼地址:github.com/zwwhnly/spr…,歡迎下載。

10.參考

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

相關文章
相關標籤/搜索