本系列博客带你一步一步的学习 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, 因为前者已经依赖于后者.
3. 配置数据源
在 resources/application.YAML 中配置数据源:
- spring:
- datasource:
- driver-class-name: com.MySQL.jdbc.Driver
- url: jdbc:MySQL://localhost:3306/springbootaction_db
- username: root
- password:
4. 修改配置文件
在 application.YAML 中添加 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 文件
- <!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>
- 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("删除错误");
- }
- }
- }
- {
- "total": 2,
- "rows": [
- {
- "authorId": 1,
- "authorName": "王卫国",
- "penName": "路遥"
- },
- {
- "authorId": 2,
- "authorName": "周树人",
- "penName": "鲁迅"
- }
- ]
- }
- {
- "authorId": 1,
- "authorName": "王卫国",
- "penName": "路遥"
- }
- {
- "total": 1,
- "rows": [
- {
- "authorId": 1,
- "authorName": "王卫国",
- "penName": "路遥"
- }
- ]
- }
来源: https://www.cnblogs.com/zwwhnly/p/11023913.html