文章目录

  • 概述
  • 搭建Spring Boot工程 Version 2.1.2.RELEASE
  • application.yml 数据库的配置
  • 集成Mybatis
    • Step1 添加依赖mybatis- spring-boot- starter
    • Step2 库表及domain类
    • Step3 添加ArtisanMapper接口
    • Step4 添加SQL映射文件
    • Step5 application.yml中配置mybatis
    • Step6 Service层编写
    • Step7 约定后台返回规范(可省略)
    • Step8 Controller编写
    • Step9 测试
  • 代码

概述

废话不多说了,直接撸吧 ,先看看整体的结构 【 Spring Boot 2.1.2 , MyBatis 1.3.2 , Mysql 8.0.13 】


搭建Spring Boot工程 Version 2.1.2.RELEASE

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 http://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.1.2.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><groupId>com.artisan</groupId><artifactId>springbootMybatis</artifactId><version>0.0.1-SNAPSHOT</version><name>springbootMybatis</name><description>Artisan </description><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><!-- spring-boot-starter-web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 对JDBC数据库的支持 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- mysql的驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- mybatis的starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><!-- 消除 Java 的冗长 ,优雅的编程 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--开发环境热部署插件 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><!-- 测试 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

pom中每个jar包都加了注释,这里就不啰嗦了。


application.yml 数据库的配置

# datasource
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driver # JDBC连接Mysql6以上com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/artisan?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=falseusername: rootpassword: root

通过上面的属性配置数据库的连接信息后, Spring Boot 就可以自动配置数据源了


集成Mybatis

Step1 添加依赖mybatis- spring-boot- starter

刚才的pom中已经有了,如下

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

Step2 库表及domain类

为了方便演示,新建库表和对应的实体类

-- ----------------------------
-- Table structure for artisan
-- ----------------------------
DROP TABLE IF EXISTS `artisan`;
CREATE TABLE `artisan` (`id` int(9) NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,`sex` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of artisan
-- ----------------------------
INSERT INTO `artisan` VALUES ('1', 'artisan', '男');
INSERT INTO `artisan` VALUES ('2', '程序媛', '女');
INSERT INTO `artisan` VALUES ('3', '周杰伦', '男');
INSERT INTO `artisan` VALUES ('4', '小笼包', '女');
INSERT INTO `artisan` VALUES ('5', '巨石强森', '男');

com.artisan.model包下新建Artisan实体类

package com.artisan.model;import lombok.Data;/*** * @author yangshangwei* *         lombok的注解 @Data 注解在类上 提供类所有属性的 getting 和 setting 方法,*         此外还提供了equals、canEqual、hashCode、toString 方法**/
@Data
public class Artisan {private Long id;private String name;private String sex;}

Step3 添加ArtisanMapper接口

com.artisan.mapper包下新建接口 ArtisanMapper

package com.artisan.mapper;import java.util.List;import org.apache.ibatis.annotations.Mapper;import com.artisan.model.Artisan;
/*** * @author yangshangwei*   * 增加@Mapper这个注解之后,Spring 启动时会自动扫描该接口,这样就可以在需要使用时直接注入 Mapper 了*/@Mapper
public interface ArtisanMapper {/***  查询全部数据*/List<Artisan> selectArtisan();}

使用了@ Mapper 注解, 增加这个注解之后,Spring 启动时会自动扫描该接口,这样就可以在需要使用时直接注入 Mapper 了


Step4 添加SQL映射文件

在 src/main/resources下面创建mapper目录,然后新建 ArtisanMapper.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接口和XML文件关联的时候, namespace的值就需要配置成接口的全限定名称 -->
<mapper namespace="com.artisan.mapper.ArtisanMapper"><select id="selectArtisan" resultType="Artisan"> <!--   resultType可以不用写全,与application.yml中的type-aliases-package属性组合使用 -->select id , name ,sex from artisan</select>
</mapper>

Step5 application.yml中配置mybatis

增加如下Mybatis的配置

#mybatis
mybatis:# 映射文件的路径 ,支持 Ant 风格的通配符, 多个配置可以使用英文逗号隔开mapper-locations: classpath:mapper/*.xml  # 类型别名包画配置,只能指定具体的包,多个配置可以使用英文逗号隔开type-aliases-package: com.artisan.model# Mybatis SQL语句控制台打印configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Step6 Service层编写

接口和实现类

package com.artisan.service;import java.util.List;import com.artisan.model.Artisan;public interface ArtisanService {List<Artisan> getArtisanList();
}
package com.artisan.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.artisan.mapper.ArtisanMapper;
import com.artisan.model.Artisan;
import com.artisan.service.ArtisanService;@Service
public class ArtisanServiceImpl implements ArtisanService {@Autowiredprivate ArtisanMapper artisanMapper;@Overridepublic List<Artisan> getArtisanList() {return artisanMapper.selectArtisan();}}

Step7 约定后台返回规范(可省略)

使用泛型封装下返回结果,见注释。 第二个包装类CodeMsg 用了lombok的注解,可以不用。Result没用,仅仅是演示下。。。

package com.artisan.result;public class Result<T> {private int code;private String msg;private T data;/*** 成功时候的调用* */public static <T> Result<T> success(T data){return new  Result<T>(data);}/*** 失败时候的调用* */public static <T> Result<T> error(CodeMsg cm){return new  Result<T>(cm);}private Result(T data) {this.code = 0;this.msg = "success";this.data = data;}private Result(CodeMsg cm) {if(cm == null) {return;}this.code = cm.getCode();this.msg = cm.getMsg();}public int getCode() {return code;}public String getMsg() {return msg;}public T getData() {return data;}
}
package com.artisan.result;import lombok.Getter;public class CodeMsg {@Getterprivate int code;@Getterprivate String msg;// 通用异常public static CodeMsg SUCCESS = new CodeMsg(0, "success");public static CodeMsg SERVER_ERROR = new CodeMsg(-1, "服务端异常");private CodeMsg(int code, String msg) {this.code = code;this.msg = msg;}}

Step8 Controller编写

package com.artisan.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import com.artisan.model.Artisan;
import com.artisan.result.CodeMsg;
import com.artisan.result.Result;
import com.artisan.service.ArtisanService;@RestController
public class ArtisanController {@Autowiredprivate ArtisanService artisanService;@GetMapping("/test")public String test() {return "artisan test";}// 正常情况@GetMapping("/artisans")public Result<List<Artisan>> selectAllArtisan() {return Result.success(artisanService.getArtisanList());}// 模拟异常情况@GetMapping("/artisansError")public Result<List<Artisan>> selectAllArtisanError() {return Result.error(CodeMsg.SERVER_ERROR);}}

Step9 测试

比较简单,各层的单元测试就不写了,直接启动测试吧

启动spring boot 工程

访问 http://localhost:8080/artisans


日志:

访问 http://localhost:8080/artisansError


代码

https://github.com/yangshangwei/springbootMybatis

Spring Boot2.x-07Spring Boot2.1.2整合Mybatis相关推荐

  1. Spring Boot2 系列教程(二十二)整合 MyBatis 多数据源

    关于多数据源的配置,前面和大伙介绍过 JdbcTemplate 多数据源配置,那个比较简单,本文来和大伙说说 MyBatis 多数据源的配置. 其实关于多数据源,我的态度还是和之前一样,复杂的就直接上 ...

  2. druid 多数据源_Spring Boot2 系列教程(二十二)整合 MyBatis 多数据源

    关于多数据源的配置,前面和大伙介绍过 JdbcTemplate 多数据源配置,那个比较简单,本文来和大伙说说 MyBatis 多数据源的配置. 其实关于多数据源,我的态度还是和之前一样,复杂的就直接上 ...

  3. MyBatis - 6.Spring整合MyBatis

    1.查看不同MyBatis版本整合Spring时使用的适配包: http://www.mybatis.org/spring/ 2.下载整合适配包 https://github.com/mybatis/ ...

  4. Spring Boot2.0 整合mybatis、分页插件、druid

    2019独角兽企业重金招聘Python工程师标准>>> 前言 本文主要是针对SpringBoot2.0.2版本,实现整合mybatis.分页插件.druid等组件,实现完整的web服 ...

  5. mybatis依赖_Spring Boot2 系列教程(二十一)整合 MyBatis

    前面两篇文章和读者聊了 Spring Boot 中最简单的数据持久化方案 JdbcTemplate,JdbcTemplate 虽然简单,但是用的并不多,因为它没有 MyBatis 方便,在 Sprin ...

  6. spring Boot 2 基础篇 。内含 整合一个spring boot 的 小案例

    目录 springBoot2基础篇 前言与开发环境 一.快速创建Boot项目 1.使用spring提供的快速构建 2.基于maven的手动构建 3.在Idea中隐藏指定文件/文件夹 二.SpringB ...

  7. 最新Spring整合MyBatis详解教程

    目录 1.导入相关jar包 1. junit 2. mybatis 3. mysql 4. spring相关 5. aop织入 6. mybatis-spring 7. lombok(选用) 2.回顾 ...

  8. Spring Boot 教程(三): Spring Boot 整合Mybatis

    教程简介 本项目内容为Spring Boot教程样例.目的是通过学习本系列教程,读者可以从0到1掌握spring boot的知识,并且可以运用到项目中.如您觉得该项目对您有用,欢迎点击收藏和点赞按钮, ...

  9. Spring Boot 整合 Mybatis Annotation 注解的完整 Web 案例

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 公司需要人.产品.业务和方向,方向又要人.产品.业务和方向,方向- 循环』 本文提纲 一 ...

最新文章

  1. 矩阵树定理2020HDU多校第6场j-Expectation[位运算+期望]
  2. Linux系统文件有三个主要的时间属性,分别是ctime(change time), atime(access time), mtime(modify time)...
  3. java(i++和++i的理解)
  4. MySQL——数据库和表的增删改查
  5. 有意思的逻辑思维题(三)(hdu2211,蓝桥杯蚂蚁感冒)
  6. Greenplum分区
  7. flask的请求与响应
  8. 光伏补贴新政出台 投资机会解析
  9. java爬虫微信公众号信息_微信公众号爬虫项目(reptile)
  10. 私生子与假婊子——谈中国手机JAVA游戏
  11. 【uart篇】synopsys uart vip配置使用
  12. 机器学习中的数学——结构化概率模型/图模型
  13. 用python求3的阶乘_Python 阶乘实例 - Python 3 基础教程
  14. I.Algorithm Choosing Mushrooms
  15. 一年回顾_2016年:一年回顾
  16. Python-OpenCV-PS油画滤镜效果
  17. 一文读懂Auth0与Azure AD的区别
  18. 完整流程Google Pay 接入
  19. 数据产品经理类型划分和工作汇报框架
  20. 计算机专业武汉的就业方向,计算机专业好就业吗

热门文章

  1. 3400g主机用linux系统,最强整合平台!锐龙5 3400G小钢炮主机配置推荐
  2. 27. Leetcode 92. 反转链表 II (链表-反转链表)
  3. 5-spark学习笔记-spark集群应用与监控
  4. NTU 课程辅助笔记: NFA到DFA的转化
  5. 从C语言的角度重构数据结构系列(六)-C语言的数据类型及常变量
  6. 强化学习(十六) 深度确定性策略梯度(DDPG)
  7. SVM-支持向量机原理详解与实践之四
  8. Python的MySQL操作
  9. mysql数据库DDL操作
  10. LeetCode-动态规划-198. 打家劫舍