目录

写在前面

最近总是有同事和技术群的朋友提问在Spring Boot中使用MyBatis时遇到的问题,大多数问题总结起来就是对MyBatis和Spring框架不熟悉的原因导致的。实际上,在Spring Boot中使用MyBatis本质就是在Spring框架中集成MyBatis,并没有其他任何高级的东西。只不过在Spring Boot中使用时因为插件封装的关系使得相关的配置可以更简洁一些,但是这种封装对于不熟悉MyBatis的人来讲反而增加了理解的难度。因此,我想把如何在Spring Boot中使用MyBatis进行一个系统性的总结,希望能有一些参考价值。

准备工作

配置数据库驱动

使用任何数据库服务器,只要是使用JDBC方式连接,都需要添加数据库驱动,甚至还需要添加数据库连接池依赖,如下配置以添加MySQL驱动为例进行说明。

  1. <!-- 添加MySQL数据库驱动 -->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. </dependency>
  6. <!-- 添加数据库连接池 -->
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>druid</artifactId>
  10. <version>${version.druid}</version>
  11. </dependency>

配置数据源

在使用数据库之前先要在Spring Boot中配置数据源,如下所示:

  1. spring:
  2. datasource:
  3. name: testDatasource
  4. driver-class-name: com.mysql.jdbc.Driver
  5. url: jdbc:mysql://127.0.0.1:3306/test_springboot
  6. username: root
  7. password:

当然,还可以配置数据库连接池:

  1. #datasource
  2. spring:
  3. datasource:
  4. name: testDatasource
  5. driver-class-name: com.mysql.jdbc.Driver
  6. url: jdbc:mysql://127.0.0.1:3306/test_springboot
  7. username: root
  8. password:
  9. # 使用druid连接池
  10. type: com.alibaba.druid.pool.DruidDataSource
  11. filters: stat
  12. maxActive: 20
  13. initialSize: 1
  14. maxWait: 60000
  15. minIdle: 1
  16. timeBetweenEvictionRunsMillis: 60000
  17. minEvictableIdleTimeMillis: 300000
  18. validationQuery: select 'x'
  19. testWhileIdle: true
  20. testOnBorrow: false
  21. testOnReturn: false
  22. poolPreparedStatements: true
  23. maxOpenPreparedStatements: 20

原生集成MyBatis

这种集成方式本质上就是在Spring框架中集成MyBatis的方式,所以在非Spring Boot框架下也可以使用。

依赖配置

首先,添加依赖配置。

  1. <!-- mybatis -->
  2. <dependency>
  3. <groupId>org.mybatis</groupId>
  4. <artifactId>mybatis</artifactId>
  5. <version>${version.mybatis}</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>tk.mybatis</groupId>
  9. <artifactId>mapper</artifactId>
  10. <version>${version.mybatis.mapper}</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.github.pagehelper</groupId>
  14. <artifactId>pagehelper</artifactId>
  15. <version>${version.pagehelper}</version>
  16. </dependency>
  17. <!-- mybatis-spring -->
  18. <dependency>
  19. <groupId>org.mybatis</groupId>
  20. <artifactId>mybatis-spring</artifactId>
  21. <version>${version.mybatis.spring}</version>
  22. </dependency>
  23. <!-- spring事务 -->
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-tx</artifactId>
  27. </dependency>
  28. <!-- spring jdbc -->
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-jdbc</artifactId>
  32. </dependency>

注册MyBatis核心组件

其次,通过Java方式在Spring框架中注册MyBatis的核心组件Bean,并且配置声明式事务管理。

(1)在Spring中注册MyBatis的核心组件Bean:SqlSessionFactory,SqlSession,以及Spring的事务管理器。另外,在构建SqlSessionFactory时还可以注册MyBatis的xml映射器。

  1. @Configuration
  2. @EnableTransactionManagement
  3. public class MyBatisSpringConfig implements TransactionManagementConfigurer {
  4. @Autowired
  5. private DataSource dataSource;
  6. // 在Spring中注册SqlSessionFactory,在这里可以设置一下参数:
  7. // 1.设置分页参数
  8. // 2.配置MyBatis运行时参数
  9. // 3.注册xml映射器
  10. @Bean
  11. public SqlSessionFactory sqlSessionFactory() {
  12. SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  13. // 设置数据源
  14. sqlSessionFactoryBean.setDataSource(dataSource);
  15. // 设置映射POJO对象包名
  16. // sqlSessionFactoryBean.setTypeAliasesPackage("org.chench.test.springboot.model");
  17. // 分页插件
  18. /*PageHelper pageHelper = new PageHelper();
  19. Properties properties = new Properties();
  20. properties.setProperty("reasonable", "true");
  21. properties.setProperty("supportMethodsArguments", "true");
  22. properties.setProperty("returnPageInfo", "check");
  23. properties.setProperty("params", "count=countSql");
  24. pageHelper.setProperties(properties);*/
  25. //添加插件
  26. //sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
  27. // 配置mybatis运行时参数
  28. org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
  29. // 自动将数据库中的下划线转换为驼峰格式
  30. configuration.setMapUnderscoreToCamelCase(true);
  31. configuration.setDefaultFetchSize(100);
  32. configuration.setDefaultStatementTimeout(30);
  33. sqlSessionFactoryBean.setConfiguration(configuration);
  34. // 在构建SqlSessionFactory时注册xml映射器
  35. ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  36. try {
  37. sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
  38. return sqlSessionFactoryBean.getObject();
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. throw new RuntimeException(e);
  42. }
  43. }
  44. /**
  45. * 注入sqlSession对象
  46. * @param sqlSessionFactory
  47. * @return
  48. */
  49. @Bean(value = "sqlSession")
  50. public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
  51. return new SqlSessionTemplate(sqlSessionFactory);
  52. }
  53. // Spring事务管理器
  54. @Bean(value = "transactionManager")
  55. @Override
  56. public PlatformTransactionManager annotationDrivenTransactionManager() {
  57. return new DataSourceTransactionManager(dataSource);
  58. }
  59. }

(2)注册MyBatis接口映射器

MyBatis 3支持2种映射器:xml映射器和接口映射器,其中xml映射器可以在构建SqlSessionFactory时进行注册。

  1. @Configuration
  2. @AutoConfigureAfter(MyBatisSpringConfig.class) //注意,由于MapperScannerConfigurer执行的比较早,所以必须有该注解
  3. public class MyBatisMapperScannerConfig {
  4. @Bean
  5. public MapperScannerConfigurer mapperScannerConfigurer() {
  6. MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
  7. // 设置sqlSessionFactory名
  8. mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
  9. // 设置接口映射器基础包名
  10. mapperScannerConfigurer.setBasePackage("org.chench.test.springboot.mapper");
  11. Properties properties = new Properties();
  12. //properties.setProperty("mappers", "org.chench.test.springboot.mapper");
  13. properties.setProperty("notEmpty", "false");
  14. properties.setProperty("IDENTITY", "MYSQL");
  15. mapperScannerConfigurer.setProperties(properties);
  16. return mapperScannerConfigurer;
  17. }
  18. }

定义并使用映射器

MyBatis支持2种类型的映射器:XML映射器和接口映射器,在这里以定义并使用接口映射器为例。

  • 定义接口映射器
  1. @Repository
  2. public interface AccountMapper {
  3. @Select("select * from account where id = #{id}")
  4. public Account getAccountById(@Param("id") long id);
  5. }

注意: 在这里可以使用Spring容器的注解@Repository声明MyBatis的接口映射器为一个Bean组件,这样在使用接口映射器时可以直接注入这个接口映射器Bean进行使用。

  • 使用接口映射器
  1. @Service
  2. public class AccountService {
  3. // 直接注入接口映射器Bean进行使用
  4. @Autowired
  5. private AccountMapper accountMapper;
  6. public Account getAccountById(long id) {
  7. return accountMapper.getAccountById(id);
  8. }
  9. }

通过MyBatis-Spring-Boot-Starter集成

通过插件MyBatis-Spring-Boot-Starter在Spring Boot中集成MyBatis时,可以不用再去关心原生配置方式里的细节,直接使用默认配置就能实现最基本的功能。当然,同样可以针对MyBatis的核心组件进行定制。所以,在这里分为2部分进行说明。第一部分说明最基础的默认集成方式,能实现在Spring Boot中使用MyBatis作为ORM插件的基本功能;第二部分说明如何在Spring Boot中对MyBatis进行高级定制。在这之前,需要先添加插件MyBatis-Spring-Boot-Starter的依赖配置。

  1. <!-- 在Spring Boot中集成MyBatis -->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>1.3.2</version>
  6. </dependency>

默认配置

默认情况下,插件MyBatis-Spring-Boot-Starter将进行如下配置:

  • 自动检查Spring Boot的数据源配置并构建DataSource对象
  • 通过SqlSessionFactoryBean使用数据源构建并注册SqlSessionFactory对象
  • 从SqlSessionFactory中创建并注册一个SqlSessionTemplate实例,其实就是构建一个SqlSession对象
  • 自动扫描接口映射器,并将这些映射器与SqlSessionTemplate实例进行关联,同时将它们注册到Spring容器中

其实上述这些默认配置就是我们在原生集成MyBatis方式中做的事情,只不过在Spring Boot中通过插件MyBatis-Spring-Boot-Starter自动完成了。只要理解了这一点,就会明白如何在Spring Boot中灵活使用MyBatis组件了。

既然MyBatis的配置已经完成了,那么下一步的工作就是如何编写和使用接口映射器。

1.定义接口映射器

  1. @Mapper
  2. public interface AccMapper {
  3. @Select("select * from account where id = #{id}")
  4. Account getAccount(@Param("id") long id);
  5. }

插件MyBatis-Spring-Boot-Starter会自动搜索使用了注解@Mapper的接口映射器并将其注册到Spring容器中,因此在这里不能使用@Repository注解标记MyBatis的映射器接口,这与原生方式集成MyBatis有所不同。

2.使用接口映射器

  1. @RestController
  2. @RequestMapping("/acc")
  3. public class AccController {
  4. // 直接通过自动注入的方式使用接口映射器
  5. @Autowired
  6. AccMapper accMapper;
  7. @GetMapping("/{id}")
  8. @ResponseBody
  9. public Object acc(@PathVariable("id") long id) {
  10. return accMapper.getAccount(id);
  11. }
  12. }

至此可以看到,在Spring Boot中通过插件MyBatis-Spring-Boot-Starter集成MyBatis时非常方便,只需要添加基本的数据源配置就可以使用了。当然,如果需要使用MyBatis更加高级的功能(如:使用xml映射器,定制MyBatis运行时参数),使用默认配置是无法实现的,必须在此基础上对MyBatis进行高级的定制。

高级定制

  • 定制MyBatis运行时参数

在Spring Boot中对MyBatis进行定制主要是指在Spring Boot的配置文件中(如:application.yaml)对MyBatis运行参数进行自定义配置(使用mybatis作为配置参数前缀):

  1. mybatis:
  2. check-config-location: true # 是否检测MyBatis运行参数配置文件
  3. config-location: classpath:/mybatis-config.xml # 指定MyBatis运行参数配置文件位置
  4. mapper-locations: classpath:/mapper/**/*.xml # 注册XML映射器
  5. type-aliases-package: test.springboot.model # 配置Java类型包名
  6. type-handlers-package: test.springboot.handlers # 配置类型处理器包名
  7. executor-type: SIMPLE # 指定执行器类型
  8. configuration:
  9. default-fetch-size: 20
  10. default-statement-timeout: 30

上述配置参数最终是通过mybatis-spring-boot-autoconfigure.jar加载和配置的。

另外,上述配置参数只是一个配置示例,详细的配置参数列表请参考MyBatis配置官网:http://www.mybatis.org/mybatis-3/zh/configuration.html

  • 注册并使用XML映射器

从定制MyBatis的运行时参数中可以看到,可以通过参数mybatis.mapper-locations指定XML映射器所在位置。

另外,可以直接通过插件MyBatis-Spring-Boot-Starter在Spring容器中注册SqlSession实例调用XML映射器,如下所示:

  1. @RestController
  2. @RequestMapping("/acc")
  3. public class AccController {
  4. // 直接注入SqlSession对象
  5. @Autowired
  6. SqlSession sqlSession;
  7. @GetMapping("/{id}")
  8. @ResponseBody
  9. public Object getById(@PathVariable("id") long id) {
  10. return sqlSession.selectOne("test.springboot.mybatis.mapper.getAccount", 1);
  11. }
  12. }
  • Java方式配置MyBatis运行时参数

MyBatis的运行时参数除了可以在Spring Boot的配置文件中指定,还可以通过Java编码方式设置。实际上就是在Spring容器中注册一个实现了ConfigurationCustomizer接口的Bean。

  1. @org.springframework.context.annotation.Configuration
  2. public class MyBatisConfigByJava {
  3. @Bean
  4. ConfigurationCustomizer mybatisConfigurationCustomizer() {
  5. return new ConfigurationCustomizer() {
  6. @Override
  7. public void customize(org.apache.ibatis.session.Configuration configuration) {
  8. // 在Spring Boot中以Java编码方式配置MyBatis运行时参数
  9. configuration.setMapUnderscoreToCamelCase(true);
  10. configuration.addMappers("org.chench.test.springboot.mapper");
  11. }
  12. };
  13. }
  14. }

更加高级的定制详见:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

总结与比较

总结起来,在Spring Boot中使用MyBatis可以使用2种方式:

  1. 使用在Spring框架中集成MyBatis的原生集成方式
  2. 使用插件MyBatis-Spring-Boot-Starter集成MyBatis

上述两种方式都可以实现对MyBatis的定制化配置,可以根据个人喜好进行选择。无论如何,要想在Spring Boot中灵活使用好MyBatis,最基础的还是MyBatis和Spring框架本身。

Spring Boot集成MyBatis的2种方式的更多相关文章

  1. 【websocket】spring boot 集成 websocket 的四种方式

    集成 websocket 的四种方案 1. 原生注解 pom.xml <dependency> <groupId>org.springframework.boot</gr ...

  2. spring boot 集成 Filter 的两种方式

    两种方式:(两种方式同时存在时,@Bean优先@ServletComponentScan实例化,生成两个对象) 1)@ServletComponentScan注解+@WebFilter注解 2)@Be ...

  3. spring boot 集成 Listener 的两种方式

    1)@ServletComponentScan注解+@WebListener注解 2)@Bean注解+ServletListenerRegistrationBean类

  4. 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法

    spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...

  5. spring boot集成mybatis(2) - 使用pagehelper实现分页

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  6. Spring Boot集成MyBatis开发Web项目

    1.Maven构建Spring Boot 创建Maven Web工程,引入spring-boot-starter-parent依赖 <project xmlns="http://mav ...

  7. Spring Boot配置过滤器的两种方式

    过滤器(Filter)是Servlet中常用的技术,可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,常用的场景有登录校验.权限控制.敏感词过滤等,下面介绍下Spring Boot配置过 ...

  8. 详解Spring Boot集成MyBatis的开发流程

    MyBatis是支持定制化SQL.存储过程以及高级映射的优秀的持久层框架,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集. spring Boot是能支持快速创建Spring应用的Java框 ...

  9. Spring Boot 整合 Shiro ,两种方式全总结!

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...

随机推荐

  1. jenkins+gitlab配置

    jenkins配置 插件配置 Jenkins要实现持续集成自动部署需要安装  gitlab  maven Publish Over SSH  Git等几个插件 查看已经安装的插件 jenkins上集成 ...

  2. 【Python 09】汇率兑换2.0-2(分支语句)

    分支语句:根据判断条件选择程序执行路径 1.使用方法 if <条件1>: <语句块1> elif <条件2>: <语句块2> ... else: < ...

  3. 无post按钮提交表单

    <form id="form1" name="form" action="url" method="GET"> ...

  4. vue 在safari动态多级面包屑导航样式不刷新的bug

    前言: 最近做公司的管理系统,用到了elementUI 里面的 bread面包屑组件,本来一切好好的,谁知道mac的safari样式全部缓存了,硬是下面这种效果,真头疼 而chrome,QQ均显示正常 ...

  5. typescript 学习笔记

    错的写法 枚举 错误写法 方法可选参 类 子类没有找父类

  6. day23--面向对象之封装、继承、多态

    面向对象的三大特性: 封装: 在类的内部(class内部)可以由属性和方法,外部代码可以通过直接调用实例变量的方法来操作数据,这样就隐藏了内部的逻辑,但是外部还是可以直接修改实例的属性,因此当需求中存 ...

  7. 3-STM32带你入坑系列(自己封装点亮一个灯的库--Keil)

    2-STM32带你入坑系列(点亮一个灯--Keil) 首先建一个stm32f103x.h的文件,然后 #include "stm32f103x.h" 还记得上一节 现在呢就是做一个 ...

  8. PostgreSql扩展Sql-动态加载共享库(C函数)

    基于 psql (PostgreSQL) 10.4 pg_language表定义了函数实现所使用的语言.主要支持了C语言和SQL语句.一些可选的语言包括pl/pgsql.tcl和perl. ligan ...

  9. redis--小白博客

    概述 redis是一种nosql数据库,他的数据是保存在内存中,同时redis可以定时把内存数据同步到磁盘,即可以将数据持久化,并且他比memcached支持更多的数据结构(string,list列表 ...

  10. c++ fmt 库安装和使用示例

    安装: 1 git clone  https://github.com/fmtlib/fmt.git 2. cmake . 3. make && make install  #incl ...