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

Apr 25, 2017 pm 03:48 PM
spring boot

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles