SpringBoot 整合 Mybatis 有两种常用的方式,一种就是我们常见的 xml 的方式 ,还有一种是全注解的方式。我觉得这两者没有谁比谁好,在 SQL 语句不太长的情况下,我觉得全注解的方式一定是比较清晰简洁的。但是,复杂的 SQL 确实不太适合和代码写在一起。

下面就开始吧!

目录:

一 开发前的准备

1.1 环境参数

  • 开发工具:IDEA
  • 基础工具:Maven+JDK8
  • 所用技术:SpringBoot+Mybatis
  • 数据库:MySQL
  • SpringBoot版本:2.1.0

1.2 创建工程

创建一个基本的 SpringBoot 项目,我这里就不多说这方面问题了,具体可以参考下面这篇文章:

https://blog.csdn.net/qq_34337272/article/details/79563606

1.3 创建数据库和 user 用户表

我们的数据库很简单,只有 4 个字段:用户 id、姓名、年龄、余额,如下图所示:

添加了“余额money”字段是为了给大家简单的演示一下事务管理的方式。

建表语句:

  1. CREATE TABLE `user` (
  2. `id` int(13) NOT NULL AUTO_INCREMENT COMMENT '主键',
  3. `name` varchar(33) DEFAULT NULL COMMENT '姓名',
  4. `age` int(3) DEFAULT NULL COMMENT '年龄',
  5. `money` double DEFAULT NULL COMMENT '账户余额',
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

1.4 配置 pom 文件中的相关依赖

由于要整合 springboot 和 mybatis 所以加入了artifactId 为 mybatis-spring-boot-starter 的依赖,由于使用了Mysql 数据库 所以加入了artifactId 为 mysql-connector-java 的依赖。

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.mybatis.spring.boot</groupId>
  8. <artifactId>mybatis-spring-boot-starter</artifactId>
  9. <version>1.3.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>mysql</groupId>
  13. <artifactId>mysql-connector-java</artifactId>
  14. <scope>runtime</scope>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-test</artifactId>
  19. <scope>test</scope>
  20. </dependency>
  21. </dependencies>

1.5 配置 application.properties

由于我使用的是比较新的Mysql连接驱动,所以配置文件可能和之前有一点不同。

  1. server.port=8333
  2. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/erp?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
  3. spring.datasource.username=root
  4. spring.datasource.password=153963
  5. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

注意:我们使用的 mysql-connector-java 8+ ,JDBC 连接到mysql-connector-java 6+以上的需要指定时区 serverTimezone=GMT%2B8。另外我们之前使用配置 Mysql数据连接是一般是这样指定driver-class-name=com.mysql.jdbc.Driver,但是现在不可以必须为 否则控制台下面的异常:

  1. Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

上面异常的意思是:com.mysql.jdbc.Driver 被弃用了。新的驱动类是 com.mysql.cj.jdbc.Driver。驱动程序通过SPI自动注册,手动加载类通常是不必要。

如果你非要写把com.mysql.jdbc.Driver 改为com.mysql.cj.jdbc.Driver 即可。

1.6 创建用户类 Bean

  1. public class User {
  2. private int id;
  3. private String name;
  4. private int age;
  5. private double money;
  6. ...
  7. 此处省略gettersetter以及 toString方法
  8. }

二 全注解的方式

先来看一下 全注解的方式,这种方式和后面提到的 xml 的方式的区别仅仅在于 一个将 sql 语句写在 java 代码中,一个写在 xml 配置文件中。全注方式解转换成 xml 方式仅需做一点点改变即可,我在后面会提到。

项目结构:

2.1 Dao 层开发

UserDao.java

  1. @Mapper
  2. public interface UserDao {
  3. /**
  4. * 通过名字查询用户信息
  5. */
  6. @Select("SELECT * FROM user WHERE name = #{name}")
  7. User findUserByName(@Param("name") String name);
  8.  
  9. /**
  10. * 查询所有用户信息
  11. */
  12. @Select("SELECT * FROM user")
  13. List<User> findAllUser();
  14.  
  15. /**
  16. * 插入用户信息
  17. */
  18. @Insert("INSERT INTO user(name, age,money) VALUES(#{name}, #{age}, #{money})")
  19. void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("money") Double money);
  20.  
  21. /**
  22. * 根据 id 更新用户信息
  23. */
  24. @Update("UPDATE user SET name = #{name},age = #{age},money= #{money} WHERE id = #{id}")
  25. void updateUser(@Param("name") String name, @Param("age") Integer age, @Param("money") Double money,
  26. @Param("id") int id);
  27.  
  28. /**
  29. * 根据 id 删除用户信息
  30. */
  31. @Delete("DELETE from user WHERE id = #{id}")
  32. void deleteUser(@Param("id") int id);
  33. }

2.2 service 层

  1. @Service
  2. public class UserService {
  3. @Autowired
  4. private UserDao userDao;
  5.  
  6. /**
  7. * 根据名字查找用户
  8. */
  9. public User selectUserByName(String name) {
  10. return userDao.findUserByName(name);
  11. }
  12.  
  13. /**
  14. * 查找所有用户
  15. */
  16. public List<User> selectAllUser() {
  17. return userDao.findAllUser();
  18. }
  19.  
  20. /**
  21. * 插入两个用户
  22. */
  23. public void insertService() {
  24. userDao.insertUser("SnailClimb", 22, 3000.0);
  25. userDao.insertUser("Daisy", 19, 3000.0);
  26. }
  27.  
  28. /**
  29. * 根据id 删除用户
  30. */
  31.  
  32. public void deleteService(int id) {
  33. userDao.deleteUser(id);
  34. }
  35.  
  36. /**
  37. * 模拟事务。由于加上了 @Transactional注解,如果转账中途出了意外 SnailClimb 和 Daisy 的钱都不会改变。
  38. */
  39. @Transactional
  40. public void changemoney() {
  41. userDao.updateUser("SnailClimb", 22, 2000.0, 3);
  42. // 模拟转账过程中可能遇到的意外状况
  43. int temp = 1 / 0;
  44. userDao.updateUser("Daisy", 19, 4000.0, 4);
  45. }
  46. }

2.3 Controller 层

  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @Autowired
  5. private UserService userService;
  6.  
  7. @RequestMapping("/query")
  8. public User testQuery() {
  9. return userService.selectUserByName("Daisy");
  10. }
  11.  
  12. @RequestMapping("/insert")
  13. public List<User> testInsert() {
  14. userService.insertService();
  15. return userService.selectAllUser();
  16. }
  17.  
  18. @RequestMapping("/changemoney")
  19. public List<User> testchangemoney() {
  20. userService.changemoney();
  21. return userService.selectAllUser();
  22. }
  23.  
  24. @RequestMapping("/delete")
  25. public String testDelete() {
  26. userService.deleteService(3);
  27. return "OK";
  28. }
  29.  
  30. }

2.4 启动类

  1. //此注解表示SpringBoot启动类
  2. @SpringBootApplication
  3. // 此注解表示动态扫描DAO接口所在包,实际上不加下面这条语句也可以找到
  4. @MapperScan("top.snailclimb.dao")
  5. public class MainApplication {
  6.  
  7. public static void main(String[] args) {
  8. SpringApplication.run(MainApplication.class, args);
  9. }
  10.  
  11. }

2.5 简单测试

上述代码经过测试都没问题,这里贴一下根据姓名查询的测试的结果。

三 xml 的方式

项目结构:

相比于注解的方式主要有以下几点改变,非常容易实现。

3.1 Dao 层的改动

我这里只演示一个根据姓名找人的方法。

UserDao.java

  1. @Mapper
  2. public interface UserDao {
  3. /**
  4. * 通过名字查询用户信息
  5. */
  6. User findUserByName(String name);
  7.  
  8. }

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4.  
  5. <mapper namespace="top.snailclimb.dao.UserDao">
  6.  
  7. <select id="findUserByName" parameterType="String" resultType="top.snailclimb.bean.User">
  8. SELECT * FROM user WHERE name = #{name}
  9. </select>
  10. </mapper>

3.2 配置文件的改动

配置文件中加入下面这句话:

mybatis.mapper-locations=classpath:mapper/*.xml

基于 SpringBoot2.0+优雅整合 SpringBoot+Mybatis的更多相关文章

  1. SpringBoot(十一):springboot2.0.2下配置mybatis generator环境,并自定义字段/getter/settetr注释

    Mybatis Generator是供开发者在mybatis开发时,快速构建mapper xml,mapper类,model类的一个插件工具.它相对来说对开发者是有很大的帮助的,但是它也有不足之处,比 ...

  2. springboot2.0+mysql整合mybatis,发现查询出来的时间比数据库datetime值快了8小时

    参考:https://blog.csdn.net/lx12345_/article/details/82020858 修改后查询数据正常

  3. 零基础IDEA整合SpringBoot + Mybatis项目,及常见问题详细解答

    开发环境介绍:IDEA + maven + springboot2.1.4 1.用IDEA搭建SpringBoot项目:File - New - Project - Spring Initializr ...

  4. 使用RESTful风格整合springboot+mybatis

    说明: 本文是springboot和mybatis的整合,Controller层使用的是RESTful风格,数据连接池使用的是c3p0,通过postman进行测试 项目结构如下: 1.引入pom.xm ...

  5. SpringBoot2.0之整合Kafka

    maven依赖: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. ...

  6. SpringBoot2.0之整合ElasticSearch

    就类比数据库到时候去实现 服务器端配置 集群名字  与yml名字一致 pom: <project xmlns="http://maven.apache.org/POM/4.0.0&qu ...

  7. SpringBoot2.0之整合ActiveMQ(发布订阅模式)

    发布订阅模式与前面的点对点模式很类似,简直一毛一样 注意:发布订阅模式 先启动消费者 公用pom: <project xmlns="http://maven.apache.org/PO ...

  8. SpringBoot2.0之整合ActiveMQ(点对点模式)

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  9. SpringBoot2.0之整合Dubbo

    Dubbo支持协议 Dubbo支持dubbo.rmi.hessian.http.webservice.thrift.redis等多种协议,但是Dubbo官网是推荐我们使用Dubbo协议的. Sprin ...

随机推荐

  1. 使用redis作为调度中心的celery时启动多个queue,报错Probably the key ('_kombu.binding.reply.celery.pidbox') has been removed from the Redis database

    我今天在使用celery启动多个queue时遇到一个问题,当启动第二个queue是,第一个启动的queue日志报了下面一段错误 [2019-12-16 14:40:25,736: ERROR/Main ...

  2. Why React Is Favored by Front-End Specialists

    In this section, we will discuss some of the features that make React a superior choice for front-en ...

  3. java获取调用当前方法的方法名和行数

    java获取调用当前方法的方法名和行数String className = Thread.currentThread().getStackTrace()[2].getClassName();//调用的 ...

  4. C#工具类MySqlHelper,基于MySql.Data.MySqlClient封装

    源码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...

  5. 15、VUEX-Store

    1.什么是VUEX Vuex是管理vue的组件状态的工具. 个人理解:vuex是管理组件之间通信的一个插件. 2.为什么要用VUEX 我们知道组件之间是独立的,组件之间想要实现通信,我目前知道的就只有 ...

  6. axios模块封装

    1.新建文件夹 network 在文件新建 request.js request.js: import axios from 'axios' export function request (conf ...

  7. RabbitMQ系列(二)环境搭建

    参考: https://www.cnblogs.com/ericli-ericli/p/5902270.html https://blog.csdn.net/weixin_30619101/artic ...

  8. doucment的获取节点的信息

    document.activeElement 返回当前获取焦点元素 document.addEventListener() 向文档添加句柄 document.adoptNode(node) 从另外一个 ...

  9. android开发中json与java对象相互转换

    json与java对象的相互转换.(使用com.google.gson) 在Android开发过程中,客户端总是需要从服务器获取数据,包括XML和json格式,目前json格式的数据使用较为普遍,所以 ...

  10. logger(三)log4j2简介及其实现原理

    一.log4j2简介 log4j2是log4j 1.x和logback的改进版,据说采用了一些新技术(无锁异步.等等),使得日志的吞吐量.性能比log4j 1.x提高10倍,并解决了一些死锁的bug, ...