文章目录

  1. 1. 环境依赖
  2. 2. 数据源3. 脚本初始化
    1. 2.1. 方案一 使用 Spring Boot 默认配置
    2. 2.2. 方案二 手动创建
  3. 4. MyBatis整合5. 总结
    1. 4.1. 方案一 通过注解的方式
      1. 4.1.1. 实体对象
      2. 4.1.2. DAO相关
      3. 4.1.3. Service相关
      4. 4.1.4. Controller相关
    2. 4.2. 方案二 通过配置文件的方式
      1. 4.2.1. 实体对象
      2. 4.2.2. 配置相关
      3. 4.2.3. DAO相关
      4. 4.2.4. Service相关
      5. 4.2.5. Controller相关
  4. 6. 源代码

本文讲解Spring Boot基础下,如何整合MyBatis框架,编写数据访问。

环境依赖

修改 POM 文件,添加mybatis-spring-boot-starter依赖。值得注意的是,可以不添加spring-boot-starter-jdbc。因为,mybatis-spring-boot-starter依赖中存在spring-boot-starter-jdbc。

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>1.1.1</version>
  5. </dependency>

添加mysql依赖。

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>5.1.35</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.0.14</version>
  10. </dependency>

数据源

方案一 使用 Spring Boot 默认配置

在 src/main/resources/application.properties 中配置数据源信息。

  1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
  3. spring.datasource.username=root
  4. spring.datasource.password=root

方案二 手动创建

在 src/main/resources/config/source.properties 中配置数据源信息。

  1. # mysql
  2. source.driverClassName = com.mysql.jdbc.Driver
  3. source.url = jdbc:mysql://localhost:3306/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
  4. source.username = root
  5. source.password = root

通过 Java Config 创建 dataSource 和jdbcTemplate 。

  1. @Configuration
  2. @EnableTransactionManagement
  3. @PropertySource(value = {"classpath:config/source.properties"})
  4. public class BeanConfig {
  5. @Autowired
  6. private Environment env;
  7. @Bean(destroyMethod = "close")
  8. public DataSource dataSource() {
  9. DruidDataSource dataSource = new DruidDataSource();
  10. dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
  11. dataSource.setUrl(env.getProperty("source.url").trim());
  12. dataSource.setUsername(env.getProperty("source.username").trim());
  13. dataSource.setPassword(env.getProperty("source.password").trim());
  14. return dataSource;
  15. }
  16. @Bean
  17. public JdbcTemplate jdbcTemplate() {
  18. JdbcTemplate jdbcTemplate = new JdbcTemplate();
  19. jdbcTemplate.setDataSource(dataSource());
  20. return jdbcTemplate;
  21. }
  22. }

脚本初始化

先初始化需要用到的SQL脚本。

  1. CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
  2. USE `springboot_db`;
  3. DROP TABLE IF EXISTS `t_author`;
  4. CREATE TABLE `t_author` (
  5. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  6. `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  7. `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

MyBatis整合

方案一 通过注解的方式

实体对象

  1. public class Author {
  2. private Long id;
  3. @JSONField(name="real_name")
  4. private String realName;
  5. @JSONField(name="nick_name")
  6. private String nickName;
  7. // SET和GET方法
  8. }

DAO相关

  1. @Mapper
  2. public interface AuthorMapper {
  3. @Insert("insert into t_author(real_name, nick_name) values(#{real_name}, #{nick_name})")
  4. int add(@Param("realName") String realName, @Param("nickName") String nickName);
  5. @Update("update t_author set real_name = #{real_name}, nick_name = #{nick_name} where id = #{id}")
  6. int update(@Param("real_name") String realName, @Param("nick_name") String nickName, @Param("id") Long id);
  7. @Delete("delete from t_author where id = #{id}")
  8. int delete(Long id);
  9. @Select("select id, real_name as realName, nick_name as nickName from t_author where id = #{id}")
  10. Author findAuthor(@Param("id") Long id);
  11. @Select("select id, real_name as realName, nick_name as nickName from t_author")
  12. List<Author> findAuthorList();
  13. }

Service相关

  1. @Service
  2. public class AuthorService {
  3. @Autowired
  4. private AuthorMapper authorMapper;
  5. public int add(String realName, String nickName) {
  6. return this.authorMapper.add(realName, nickName);
  7. }
  8. public int update(String realName, String nickName, Long id) {
  9. return this.authorMapper.update(realName, nickName, id);
  10. }
  11. public int delete(Long id) {
  12. return this.authorMapper.delete(id);
  13. }
  14. public Author findAuthor(Long id) {
  15. return this.authorMapper.findAuthor(id);
  16. }
  17. public List<Author> findAuthorList() {
  18. return this.authorMapper.findAuthorList();
  19. }
  20. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController("mybatis.authorController")
  2. @RequestMapping(value="/data/mybatis/author")
  3. @MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
  4. public class AuthorController {
  5. @Autowired
  6. private AuthorService authorService;
  7. /**
  8. * 查询用户列表
  9. */
  10. @RequestMapping(method = RequestMethod.GET)
  11. public Map<String,Object> getAuthorList(HttpServletRequest request) {
  12. List<Author> authorList = this.authorService.findAuthorList();
  13. Map<String,Object> param = new HashMap<String,Object>();
  14. param.put("total", authorList.size());
  15. param.put("rows", authorList);
  16. return param;
  17. }
  18. /**
  19. * 查询用户信息
  20. */
  21. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  22. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  23. Author author = this.authorService.findAuthor(userId);
  24. if(author == null){
  25. throw new RuntimeException("查询错误");
  26. }
  27. return author;
  28. }
  29. /**
  30. * 新增方法
  31. */
  32. @RequestMapping(method = RequestMethod.POST)
  33. public void add(@RequestBody JSONObject jsonObject) {
  34. String userId = jsonObject.getString("user_id");
  35. String realName = jsonObject.getString("real_name");
  36. String nickName = jsonObject.getString("nick_name");
  37. try{
  38. this.authorService.add(realName, nickName);
  39. }catch(Exception e){
  40. e.printStackTrace();
  41. throw new RuntimeException("新增错误");
  42. }
  43. }
  44. /**
  45. * 更新方法
  46. */
  47. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
  48. public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
  49. Author author = this.authorService.findAuthor(userId);
  50. String realName = jsonObject.getString("real_name");
  51. String nickName = jsonObject.getString("nick_name");
  52. try{
  53. this.authorService.update(realName, nickName, author.getId());
  54. }catch(Exception e){
  55. e.printStackTrace();
  56. throw new RuntimeException("更新错误");
  57. }
  58. }
  59. /**
  60. * 删除方法
  61. */
  62. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
  63. public void delete(@PathVariable Long userId) {
  64. try{
  65. this.authorService.delete(userId);
  66. }catch(Exception e){
  67. throw new RuntimeException("删除错误");
  68. }
  69. }
  70. }

方案二 通过配置文件的方式

实体对象

  1. public class Author {
  2. private Long id;
  3. @JSONField(name="real_name")
  4. private String realName;
  5. @JSONField(name="nick_name")
  6. private String nickName;
  7. // SET和GET方法
  8. }

配置相关

在 src/main/resources/mybatis/AuthorMapper.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. <mapper namespace="com.lianggzone.springboot.action.data.mybatis.dao.AuthorMapper2">
  5. <!-- type为实体类Student,包名已经配置,可以直接写类名 -->
  6. <resultMap id="authorMap" type="Author">
  7. <id property="id" column="id" />
  8. <result property="realName" column="real_name" />
  9. <result property="nickName" column="nick_name" />
  10. </resultMap>
  11. <select id="findAuthor" resultMap="authorMap" resultType="Author">
  12. select id, real_name, nick_name from t_author where id = #{id}
  13. </select>
  14. </mapper>

在 src/main/resources/application.properties 中配置数据源信息。

  1. mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml
  2. mybatis.type-aliases-package=com.lianggzone.springboot.action.data.mybatis.entity

DAO相关

  1. public interface AuthorMapper2 {
  2. Author findAuthor(@Param("id") Long id);
  3. }

Service相关

  1. @Service
  2. public class AuthorService2 {
  3. @Autowired
  4. private AuthorMapper2 authorMapper;
  5. public Author findAuthor(Long id) {
  6. return this.authorMapper.findAuthor(id);
  7. }
  8. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController("mybatis.authorController2")
  2. @RequestMapping(value="/data/mybatis/author2")
  3. @MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
  4. public class AuthorController2 {
  5. @Autowired
  6. private AuthorService2 authorService;
  7. /**
  8. * 查询用户信息
  9. */
  10. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  11. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  12. Author author = this.authorService.findAuthor(userId);
  13. if(author == null){
  14. throw new RuntimeException("查询错误");
  15. }
  16. return author;
  17. }
  18. }

总结

上面这个简单的案例,让我们看到了 Spring Boot 整合 MyBatis 框架的大概流程。那么,复杂的场景,大家可以参考使用一些比较成熟的插件,例如com.github.pagehelper、mybatis-generator-maven-plugin等。

源代码

相关示例完整代码: springboot-action

(完)

如果觉得我的文章对你有帮助,请随意打赏。

Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合的更多相关文章

  1. Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理

    文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...

  2. Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch

    文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...

  3. Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用mongoTemplate操作4. 总结 3.1. 实体对象 3 ...

  4. Spring Boot 揭秘与实战(二) 数据存储篇 - Redis

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...

  5. Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合

    文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...

  6. Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置

    文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...

  7. Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. 使用JdbcTemplate操作5. 总结 4.1. ...

  8. Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门

    文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...

  9. Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache

    文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...

随机推荐

  1. poj-2888-矩阵+polya

    Magic Bracelet Time Limit: 2000MS   Memory Limit: 131072K Total Submissions: 6195   Accepted: 1969 D ...

  2. MySQL5.6复制技术(2)-主从部署以及半同步配置详细过程

    当前环境规划 主机名称 ec2t-pgtest-01 ec2t-pgtest-02 IP地址 10.189.102.118 10.189.100.195 角色 master slave 系统版本 Ce ...

  3. echarts的基本使用

    echarts的基本使用 官网:http://echarts.baidu.com/index.html ECharts,一个使用 JavaScript 实现的开源可视化库,可以流畅的运行在 PC 和移 ...

  4. NOIP2015神奇的幻方

    题目描述 幻方是一种很神奇的 N∗N 矩阵:它由数字1,2,3,⋯⋯,N×N 构成,且每行.每列及两条对角线上的数字之和都相同. 当 N 为奇数时,我们可以通过下方法构建一个幻方: 首先将 1 写在第 ...

  5. SourceInsight 4重启之后文件变只读无法编辑

    SourceInsight4.0在导入代码后,用起来没问题,第二天,再开启sourceInsight,结果所有文件变成只读了,不能编辑,标签前面也有了叹号. 百度一下,有人说是版本控制的问题,但是sv ...

  6. 同步socket处理

    1.socket类是TCP通信的基本类,调用成员函数connect()可以连接到一个指定的通信端点,连接成功后用local_endpoint()和remote_endpoint()获得连接两端的端点信 ...

  7. 蓝桥杯—BASIC-19 完美的代价(贪心)

    问题描述 回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的.小龙龙认为回文串才是完美的. 现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串. 交换的定义 ...

  8. POJ 1035 Spell checker 字符串 难度:0

    题目 http://poj.org/problem?id=1035 题意 字典匹配,单词表共有1e4个单词,单词长度小于15,需要对最多50个单词进行匹配.在匹配时,如果直接匹配可以找到待匹配串,则直 ...

  9. WPS处理个人信息一种方法

    下面是WPS处理个人信息的方法,具体步骤如下: 第一步:任意打开一个文件: 第二步:点击左上角WPS的小三角,找到工具——选项,如图: 第三步:进入选项后,点击用户信息: 第四步:修改个人信息,用户名 ...

  10. SpringBoot document notes

    图片拷贝不过来,直接从github上下载 . 链接: https://github.com/DFX339/SpringBootDocumentNotes.git Create a example po ...