Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the two ways of integrating MyBatis into the SpringBoot standard

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

What are the two ways of integrating MyBatis into the SpringBoot standard? in order to solve this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Write at the front

Most of the recent problems that many people encounter when using MyBatis in Spring Boot are summed up as a result of unfamiliarity with MyBatis and the Spring framework. In fact, the essence of using MyBatis in Spring Boot is to integrate MyBatis into the Spring framework, without any other advanced stuff. It's just that when used in Spring Boot, the relevant configuration can be more concise because of plug-in encapsulation, but this encapsulation makes it more difficult for people who are not familiar with MyBatis to understand. Therefore, I would like to make a systematic summary of how to use MyBatis in Spring Boot, hoping to have some reference value.

Prepare to configure the database driver

Using any database server, as long as you connect using JDBC, you need to add a database driver and even a database connection pool dependency. The following configuration takes adding a MySQL driver as an example.

Mysql

Mysql-connector-java

Com.alibaba

Druid

${version.druid}

Configure the data source

Configure the data source in Spring Boot before using the database, as follows:

Spring:

Datasource:

Name: testDatasource

Driver-class-name: com.mysql.jdbc.Driver

Url: jdbc:mysql://127.0.0.1:3306/test_springboot

Username: root

Password:

Of course, you can also configure database connection pooling:

# datasource

Spring:

Datasource:

Name: testDatasource

Driver-class-name: com.mysql.jdbc.Driver

Url: jdbc:mysql://127.0.0.1:3306/test_springboot

Username: root

Password:

# using druid connection pooling

Type: com.alibaba.druid.pool.DruidDataSource

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

Native integrated MyBatis

This integration approach is essentially the way to integrate MyBatis in the Spring framework, so it can also be used in non-Spring Boot frameworks.

Dependent configuration

First, add a dependency configuration.

Org.mybatis

Mybatis

${version.mybatis}

Tk.mybatis

Mapper

${version.mybatis.mapper}

Com.github.pagehelper

Pagehelper

${version.pagehelper}

Org.mybatis

Mybatis-spring

${version.mybatis.spring}

Org.springframework

Spring-tx

Org.springframework

Spring-jdbc

Register MyBatis core components

Secondly, register Bean, the core component of MyBatis, in the Spring framework through Java, and configure declarative transaction management.

(1) register Bean:SqlSessionFactory,SqlSession, the core component of MyBatis, and the transaction manager of Spring in Spring. In addition, you can register MyBatis's xml mapper when building SqlSessionFactory.

@ Configuration

@ EnableTransactionManagement

Public class MyBatisSpringConfig implements TransactionManagementConfigurer {

@ Autowired

Private DataSource dataSource

/ / register SqlSessionFactory in Spring, where you can set the following parameters:

/ / 1. Set paging parameters

/ / 2. Configure MyBatis runtime parameters

/ / 3. Register the xml mapper

@ Bean

Public SqlSessionFactory sqlSessionFactory () {

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean ()

/ / set the data source

SqlSessionFactoryBean.setDataSource (dataSource)

/ / set the mapping POJO object package name

/ / sqlSessionFactoryBean.setTypeAliasesPackage ("org.chench.test.springboot.model")

/ / paging plug-in

/ * 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); * /

/ / add plug-ins

/ / sqlSessionFactoryBean.setPlugins (new Interceptor [] {pageHelper})

/ / configure mybatis runtime parameters

Org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration ()

/ / automatically convert underscores in the database to hump format

Configuration.setMapUnderscoreToCamelCase (true)

Configuration.setDefaultFetchSize (100)

Configuration.setDefaultStatementTimeout (30)

SqlSessionFactoryBean.setConfiguration (configuration)

/ / register the xml mapper when building the SqlSessionFactory

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver ()

Try {

SqlSessionFactoryBean.setMapperLocations (resolver.getResources ("classpath:mapper/*.xml"))

Return sqlSessionFactoryBean.getObject ()

} catch (Exception e) {

E.printStackTrace ()

Throw new RuntimeException (e)

}

}

/ * *

* inject sqlSession object

* @ param sqlSessionFactory

* @ return

, /

@ Bean (value = "sqlSession")

Public SqlSessionTemplate sqlSessionTemplate (SqlSessionFactory sqlSessionFactory) {

Return new SqlSessionTemplate (sqlSessionFactory)

}

/ / Spring transaction Manager

@ Bean (value = "transactionManager")

@ Override

Public PlatformTransactionManager annotationDrivenTransactionManager () {

Return new DataSourceTransactionManager (dataSource)

}

}

(2) register the MyBatis interface mapper

MyBatis 3 supports two types of mappers: the xml mapper and the interface mapper, where the xml mapper can be registered when the SqlSessionFactory is built.

@ Configuration

@ AutoConfigureAfter (MyBatisSpringConfig.class) / / Note that this comment is required because MapperScannerConfigurer executes early

Public class MyBatisMapperScannerConfig {

@ Bean

Public MapperScannerConfigurer mapperScannerConfigurer () {

MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer ()

/ / set the sqlSessionFactory name

MapperScannerConfigurer.setSqlSessionFactoryBeanName ("sqlSessionFactory")

/ / set the interface mapper base package name

MapperScannerConfigurer.setBasePackage ("org.chench.test.springboot.mapper")

Properties properties = new Properties ()

/ / properties.setProperty ("mappers", "org.chench.test.springboot.mapper")

Properties.setProperty ("notEmpty", "false")

Properties.setProperty ("IDENTITY", "MYSQL")

MapperScannerConfigurer.setProperties (properties)

Return mapperScannerConfigurer

}

}

Define and use the mapper

MyBatis supports two types of mappers: the XML mapper and the interface mapper, which are defined and used here as an example.

Define interface mapper

@ Repository

Public interface AccountMapper {

@ Select ("select * from account where id = # {id}")

Public Account getAccountById (@ Param ("id") long id)

}

Note: here you can use the @ Repository annotation of the Spring container to declare that MyBatis's interface mapper is a Bean component, so that when using the interface mapper, you can directly inject the interface mapper Bean for use.

Use the interface mapper

@ Service

Public class AccountService {

/ / directly inject the interface mapper Bean for use

@ Autowired

Private AccountMapper accountMapper

Public Account getAccountById (long id) {

Return accountMapper.getAccountById (id)

}

}

Integration through MyBatis-Spring-Boot-Starter

When integrating MyBatis into Spring Boot through the plug-in MyBatis-Spring-Boot-Starter, you can no longer care about the details of the native configuration, and you can directly use the default configuration to achieve the most basic functions. Of course, it can also be customized for the core components of MyBatis. Therefore, it is divided into two parts to explain here. The first part describes the most basic default integration method, which can achieve the basic function of using MyBatis as the ORM plug-in in Spring Boot; the second part explains how to make advanced customization of MyBatis in Spring Boot. Before that, you need to add the dependency configuration of the plug-in MyBatis-Spring-Boot-Starter.

Org.mybatis.spring.boot

Mybatis-spring-boot-starter

1.3.2

Default configuration

By default, the plug-in MyBatis-Spring-Boot-Starter is configured as follows:

Automatically check the data source configuration of Spring Boot and build DataSource objects

Build and register SqlSessionFactory objects using data sources through SqlSessionFactoryBean

To create and register a SqlSessionTemplate instance from SqlSessionFactory is to build a SqlSession object

Automatically scans interface mappers and associates them with SqlSessionTemplate instances while registering them in the Spring container

In fact, the above default configuration is what we do in the native integration MyBatis mode, but it is done automatically in Spring Boot through the plug-in MyBatis-Spring-Boot-Starter. As long as you understand this, you will understand how to use MyBatis components flexibly in Spring Boot. Now that the MyBatis is configured, the next step is how to write and use the interface mapper.

1. Define interface mapper

@ Mapper

Public interface AccMapper {

@ Select ("select * from account where id = # {id}")

Account getAccount (@ Param ("id") long id)

}

The plug-in MyBatis-Spring-Boot-Starter automatically searches for interface mappers that use the annotation @ Mapper and registers them with the Spring container, so you cannot mark MyBatis's mapper interface with the @ Repository annotation here, which is different from the native integration of MyBatis.

two。 Use the interface mapper

@ RestController

@ RequestMapping ("/ acc")

Public class AccController {

/ / use the interface mapper directly through automatic injection

@ Autowired

AccMapper accMapper

@ GetMapping ("/ {id}")

@ ResponseBody

Public Object acc (@ PathVariable ("id") long id) {

Return accMapper.getAccount (id)

}

}

As you can see, it is very convenient to integrate MyBatis through the plug-in MyBatis-Spring-Boot-Starter in Spring Boot, and you only need to add basic data source configuration to use it. Of course, if you need to use more advanced features of MyBatis (such as using the xml mapper to customize MyBatis runtime parameters), it is impossible to use the default configuration, and you must make advanced customizations to MyBatis on this basis.

Advanced customization

Customize MyBatis runtime parameters

Customizing MyBatis in Spring Boot mainly refers to the custom configuration of MyBatis running parameters in the configuration file of Spring Boot (such as application.yaml) (using mybatis as the prefix of configuration parameters):

Mybatis:

Check-config-location: whether true # detects the MyBatis running parameter configuration file

Config-location: classpath:/mybatis-config.xml # specifies the location of the MyBatis running parameter configuration file

Mapper-locations: classpath:/mapper/**/*.xml # registers the XML mapper

Type-aliases-package: test.springboot.model # configure Java type package name

Type-handlers-package: test.springboot.handlers # configuration type processor package name

Executor-type: SIMPLE # specifies the actuator type

Configuration:

Default-fetch-size: 20

Default-statement-timeout: 30

The above configuration parameters are ultimately loaded and configured through mybatis-spring-boot-autoconfigure.jar.

In addition, the above configuration parameters are only a configuration example. For a detailed list of configuration parameters, please refer to the MyBatis configuration official website: http://www.mybatis.org/mybatis-3/zh/configuration.html.

Register and use the XML mapper

As you can see from the runtime parameters of the custom MyBatis, you can specify the location of the XML mapper through the parameter mybatis.mapper-locations. In addition, you can call the XML mapper directly through the plug-in MyBatis-Spring-Boot-Starter to register the SqlSession instance in the Spring container, as shown below:

@ RestController

@ RequestMapping ("/ acc")

Public class AccController {

/ / directly inject SqlSession objects

@ Autowired

SqlSession sqlSession

@ GetMapping ("/ {id}")

@ ResponseBody

Public Object getById (@ PathVariable ("id") long id) {

Return sqlSession.selectOne ("test.springboot.mybatis.mapper.getAccount", 1)

}

}

Configure MyBatis runtime parameters in Java mode

In addition to being specified in the configuration file of Spring Boot, the runtime parameters of MyBatis can also be set by Java encoding. You are actually registering a Bean that implements the ConfigurationCustomizer interface in the Spring container.

@ org.springframework.context.annotation.Configuration

Public class MyBatisConfigByJava {

@ Bean

ConfigurationCustomizer mybatisConfigurationCustomizer () {

Return new ConfigurationCustomizer () {

@ Override

Public void customize (org.apache.ibatis.session.Configuration configuration) {

/ / configure MyBatis runtime parameters in Java encoding in Spring Boot

Configuration.setMapUnderscoreToCamelCase (true)

Configuration.addMappers ("org.chench.test.springboot.mapper")

}

}

}

}

For more advanced customization, see http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/.

Summary and comparison

To sum up, there are two ways to use MyBatis in Spring Boot:

Using the native integration approach to integrating MyBatis in the Spring framework

Integrate MyBatis using the plug-in MyBatis-Spring-Boot-Starter

In any case, if you want to make good use of MyBatis flexibly in Spring Boot, the most basic thing is the MyBatis and Spring framework itself.

The answer to the question about the two ways of integrating MyBatis in SpringBoot standard is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report