Home > Java > javaTutorial > Detailed explanation of the java instance of Spring Boot integrating MyBatis

Detailed explanation of the java instance of Spring Boot integrating MyBatis

Y2J
Release: 2017-04-25 15:48:48
Original
1666 people have browsed it

Spring Boot is a new framework provided by the Pivotal team. It is designed to simplify the initial construction and development process of new Spring applications. The framework uses an ad hoc approach to configuration, eliminating the need for developers to define boilerplate configurations. In this way, Spring Boot strives to become a leader in the booming field of rapid application development.

Before integrating MyBatis, we first configure a druid data source.

Spring Boot Series

1. Getting started with Spring Boot

2. Spring Boot property configuration and usage

3.Spring Boot integrates MyBatis

4.Spring Boot static resource processing

5.Spring Boot - configuration sorting dependency skills

Spring Boot Integrating druid

druid has many configuration options. Druid can be easily configured using the spring Boot configuration file.

Write in the application.yml configuration file:

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
Copy after login

Configure here through type: com.alibaba.druid.pool.DruidDataSource!

Spring Boot integrates MyBatis

There are two ways to integrate Spring Boot with MyBatis. A simple way is to use the official MyBatis solution:

mybatis-spring-boot-starter

Another way is to still use a configuration method similar to mybatis-spring. This method requires you to write some code yourself, but it can easily control MyBatis. Various configurations.

1. mybatis-spring-boot-starter method

Add dependencies in pom.xml:

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

mybatis The -spring-boot-starter dependency tree is as follows:

Detailed explanation of the java instance of Spring Boot integrating MyBatis

The 3.3.0 version used by mybatis can be passed:

3.3 The .0 property modifies the default version.

mybatis-spring uses version 1.2.3. You can modify the default version through:

1.2.3.

Add configuration in application.yml:

mybatis:

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

In addition to the two common configurations above, there are also:

  • mybatis.config: the path to the mybatis-config.xml configuration file

  • mybatis.typeHandlersPackage: Scan the package of typeHandlers

  • mybatis.checkConfigLocation: Check whether the configuration file exists

  • mybatis.executorType: Set execution mode ( SIMPLE, REUSE, BATCH), the default is SIMPLE

2. mybatis-spring method

This method is the same as Common usage is relatively close. You need to add mybatis dependency and mybatis-spring dependency.

Then create a MyBatisConfig configuration class:

/**
 * 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);
 }
}
Copy after login

The above code creates a SqlSessionFactory and a SqlSessionTemplate. In order to support annotation transactions, the @EnableTransactionManagement annotation is added and a PlatformTransactionManagerBean is returned.

It should also be noted that there is no MapperScannerConfigurer in this configuration. If we want to scan the Mapper interface of MyBatis, we need to configure this class. We need to put this configuration in a separate class.

/**
 * 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;
 }
}
Copy after login

Be sure to pay attention to @AutoConfigureAfter(MyBatisConfig.class) in this configuration. This configuration must be present, otherwise there will be exceptions. The reason is that this class is executed relatively early, and since sqlSessionFactory does not exist yet, subsequent execution errors occur.

After completing the above configuration, you can use MyBatis.

About the integration of paging plug-in and universal Mapper

The example of paging plug-in as a plug-in is in the above code.

General Mapper configuration is actually to use tk.mybatis.spring.mapper.MapperScannerConfigurer when configuring MapperScannerConfigurer, and use Properties for configuration properties.

Spring Boot integrates the basic project of MyBatis

I uploaded to github an integration project using the second method, and integrated the paging plug-in and general Mapper. The project contains simple configuration and operation , for reference only.

Project address: https://github.com/abel533/MyBatis-Spring-Boot

Related information about the paging plug-in and general Mapper can be found at the above address.

Related references:

Spring Boot Quick Start Guide

Spring Boot Quick Start Tutorial

The above is the detailed content of Detailed explanation of the java instance of Spring Boot integrating MyBatis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template