温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot 如何实现与MyBatis搭配使用

发布时间:2020-11-12 16:36:39 来源:亿速云 阅读:157 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关Spring Boot 如何实现与MyBatis搭配使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

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

Spring Boot 系列

1.Spring Boot 入门

2.Spring Boot 属性配置和使用

3.Spring Boot 集成MyBatis

4.Spring Boot 静态资源处理

5.Spring Boot - 配置排序依赖技巧

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基础配置
 *
 * @author liuzh
 * @since 2015-12-19 10:11
 */
@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扫描接口
 * 
 * @author liuzh
 * @since 2015-12-19 14:46
 */
@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搭配使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI