Spring Boot集成MyBatis的方法

作者:isea533 时间:2021-11-03 23:11:05 

Spring Boot 集成MyBatis

在集成MyBatis前,我们先配置一个druid数据源。

Spring Boot 集成druid

druid有很多个配置选项,使用Spring Boot 的配置文件可以方便的配置druid

application.yml配置文件中写上:


spring:
 datasource:
   name: test
   url: jdbc:mysql://192.168.16.137:3306/test
   username: root
   password:
   # 使用druid数据源
   type: com.alibaba.druid.pool.DruidDataSource
   driver-class-name: com.mysql.jdbc.Driver
   filters: stat
   maxActive: 20
   initialSize: 1
   maxWait: 60000
   minIdle: 1
   timeBetweenEvictionRunsMillis: 60000
   minEvictableIdleTimeMillis: 300000
   validationQuery: select 'x'
   testWhileIdle: true
   testOnBorrow: false
   testOnReturn: false
   poolPreparedStatements: true
   maxOpenPreparedStatements: 20

这里通过type: com.alibaba.druid.pool.DruidDataSource配置即可!

Spring Boot 集成MyBatis

Spring Boot 集成MyBatis有两种方式,一种简单的方式就是使用MyBatis官方提供的:

mybatis-spring-boot-starter

另外一种方式就是仍然用类似mybatis-spring的配置方式,这种方式需要自己写一些代码,但是可以很方便的控制MyBatis的各项配置。

一、mybatis-spring-boot-starter方式

pom.xml中添加依赖:


<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>1.0.0</version>
</dependency>

mybatis-spring-boot-starter依赖树如下:

Spring Boot集成MyBatis的方法

  • 其中mybatis使用的3.3.0版本,可以通过: <mybatis.version>3.3.0</mybatis.version>属性修改默认版本。

  • mybatis-spring使用版本1.2.3,可以通过: <mybatis-spring.version>1.2.3</mybatis-spring.version>修改默认版本。

在application.yml中增加配置:


mybatis:
mapperLocations: classpath:mapper/*.xml
typeAliasesPackage: tk.mapper.model

除了上面常见的两项配置,还有:

  • mybatis.config:mybatis-config.xml配置文件的路径

  • mybatis.typeHandlersPackage:扫描typeHandlers的包

  • mybatis.checkConfigLocation:检查配置文件是否存在

  • mybatis.executorType:设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE

二、mybatis-spring方式

这种方式和平常的用法比较接近。需要添加mybatis依赖和mybatis-spring依赖。

然后创建一个MyBatisConfig配置类:


/**
* MyBatis基础配置
*/
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
 @Autowired
 DataSource dataSource;
 @Bean(name = "sqlSessionFactory")
 public SqlSessionFactory sqlSessionFactoryBean() {
   SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
   bean.setDataSource(dataSource);
   bean.setTypeAliasesPackage("tk.mybatis.springboot.model");
   //分页插件
   PageHelper pageHelper = new PageHelper();
   Properties properties = new Properties();
   properties.setProperty("reasonable", "true");
   properties.setProperty("supportMethodsArguments", "true");
   properties.setProperty("returnPageInfo", "check");
   properties.setProperty("params", "count=countSql");
   pageHelper.setProperties(properties);
   //添加插件
   bean.setPlugins(new Interceptor[]{pageHelper});
   //添加XML目录
   ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
   try {
     bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
     return bean.getObject();
   } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
   }
 }
 @Bean
 public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
   return new SqlSessionTemplate(sqlSessionFactory);
 }
 @Bean
 @Override
 public PlatformTransactionManager annotationDrivenTransactionManager() {
   return new DataSourceTransactionManager(dataSource);
 }
}

上面代码创建了一个SqlSessionFactory和一个SqlSessionTemplate,为了支持注解事务,增加了@EnableTransactionManagement注解,并且反回了一个PlatformTransactionManagerBean

另外应该注意到这个配置中没有MapperScannerConfigurer,如果我们想要扫描MyBatis的Mapper接口,我们就需要配置这个类,这个配置我们需要单独放到一个类中。


/**
* MyBatis扫描接口
*/
@Configuration
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
 @Bean
 public MapperScannerConfigurer mapperScannerConfigurer() {
   MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
   mapperScannerConfigurer.setBasePackage("tk.mybatis.springboot.mapper");
   return mapperScannerConfigurer;
 }
}

这个配置一定要注意@AutoConfigureAfter(MyBatisConfig.class),必须有这个配置,否则会有异常。原因就是这个类执行的比较早,由于sqlSessionFactory还不存在,后续执行出错。

做好上面配置以后就可以使用MyBatis了。

关于分页插件和通用Mapper集成

分页插件作为插件的例子在上面代码中有。

通用Mapper配置实际就是配置MapperScannerConfigurer的时候使用tk.mybatis.spring.mapper.MapperScannerConfigurer即可,配置属性使用Properties

Spring Boot集成MyBatis的基础项目

我上传到github一个采用第二种方式的集成项目,并且集成了分页插件和通用Mapper,项目包含了简单的配置和操作,仅作为参考。

项目地址:https://github.com/abel533/MyBatis-Spring-Boot

分页插件和通用Mapper的相关信息可以通过上面地址找到。

来源:https://blog.csdn.net/isea533/article/details/50359390

标签:spring,boot,mybatis,集成
0
投稿

猜你喜欢

  • 基于java集合中的一些易混淆的知识点(详解)

    2023-08-29 03:06:26
  • Android植物大战僵尸小游戏

    2023-08-05 21:27:04
  • Java实现验证码具体代码(图片、汉字)

    2023-03-25 11:14:31
  • Java List分页功能实现代码实例

    2022-06-02 13:56:14
  • Springboot配置文件内容加密代码实例

    2022-09-13 05:56:09
  • Kotlin之在Gradle中无参(no-arg)编译器插件的使用详解

    2023-07-31 19:11:43
  • windows 部署JAVA环境安装iDea的详细步骤

    2022-10-09 01:09:26
  • java定时任务Timer和TimerTask使用详解

    2023-07-13 00:29:33
  • Java与C++分别用递归实现汉诺塔详解

    2021-10-23 01:28:59
  • 同时使用@LoadBalanced @RefreshScope注解负载均衡失效分析

    2023-12-07 10:59:24
  • java中使用数组进行模拟加密的方法

    2023-11-18 15:37:39
  • Java关键字详解之final static this super的用法

    2022-01-19 09:24:39
  • Flutter加载图片流程MultiFrameImageStreamCompleter解析

    2023-07-19 02:45:55
  • Java 开启多线程常见的4种方法

    2023-11-23 02:30:10
  • 解析spring加载bean流程的方法

    2023-11-29 13:50:32
  • java寻找迷宫路径的简单实现示例

    2021-07-06 13:17:50
  • Springboot轻量级的监控组件SpringbootAdmin

    2023-08-25 10:08:31
  • Spring Security内置过滤器的维护方法

    2022-07-30 18:10:16
  • 深入理解Java高级特性——注解

    2021-05-23 20:28:54
  • c#中CAD文件读取实例

    2023-07-23 19:37:59
  • asp之家 软件编程 m.aspxhome.com