Detailed explanation of the java instance of Spring Boot integrating MyBatis
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
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>
mybatis The -spring-boot-starter dependency tree is as follows:
The 3.3.0 version used by mybatis can be passed:
mybatis-spring uses version 1.2.3. You can modify the default version through:
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); } }
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; } }
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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1
Easy-to-use and free code editor