MyBatis seamless butt Spring method
- 2020-09-28 08:52:11
- OfStack
1. Why does ES1en-ES2en appear
Spring framework and MyBatis framework are the mainstream of Java Internet technology. But how do you integrate MyBatis seamlessly into the Spring framework? This was the birth of ES10en-ES11en. Using the classes from the class library, Spring will load the necessary MyBatis factory classes and session classes.
Spring3.0 also supports es18EN2.0 only. Support for MyBatis3 would have been added to Spring3.0. Unfortunately, development of Spring3.0 ended before the official es22EN3.0 release. Because the Spring development team did not want to release a non-release version of MyBatis's integration support. They dropped their support for MyBatis.
As Spring becomes more and more the technical framework for the java DE facto standard. Spring 4.0 removes direct support for iBatis. The MyBatis team developed MyBatis integration based on Spring -- ES36en-ES37en.
2. Benefits of using ES40en-Spring
1. Better separation of business layer and model layer. MyBatis in Spring framework is also simpler, saving a lot of code
2. Use SqlSessionFactory, SqlSessiond and other objects without even needing to be displayed
3. MyBatis-Spring component
1. Configure the data source
2. Configuration SqlSessionFactory
3. The configuration SqlSessionTemplate
4. Configuration Mapper
5. Transaction processing
The SqlSessionFactory object is built in MyBatis to produce SqlSession, while the use of SqlSession in the ES72en-ES73en project is achieved through SqlSessionTemplate, which provides encapsulation of the SqlSession operation. So Mapper is available through SqlSessionTemplate.
4. Configuration in Spring MVC
4.1 configuration SqlSessionFactoryBean
In the basic MyBatis,session factories can be created using SqlSessionFactoryBuilder. In ES91en-ES92en, SqlSessionFactoryBean is used instead.
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
Pay attention to the point
SqlSessionFactory has a single required attribute, DataSource of JDBC
When SqlSessionFactoryBean returns getObject, there is a validation.
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
@Override
public void afterPropertiesSet() throws Exception {
notNull(dataSource, "Property 'dataSource' is required");
notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
"Property 'configuration' and 'configLocation' can not specified with together");
this.sqlSessionFactory = buildSqlSessionFactory();
}
4.2 configuration datasource
Here we use Alibaba's database connection pool. https://github.com/alibaba/druid
compile group: 'com.alibaba', name: 'druid', version: '1.1.2'
<!-- Alibaba's database connection pool -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- Basic attributes url , user , password -->
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_user}"/>
<property name="password" value="${jdbc_password}"/>
</bean>
4.3 Configure database link properties
Create the properties folder under the resource directory and create datasource.properties
jdbc_url=jdbc:mysql://localhost:3306/cnblogs?serverTimezone=Asia/Shanghai&characterEncoding=utf8
jdbc_user=root
jdbc_password=root
There is no need to configure the database driver to use Alibaba's database connection pool. Is determined by the prefix of url
4.4 Configure Spring to load configuration properties and configure alternative dynamic tags
<!-- Load the configuration file path -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:properties/datasource.properties"></property>
</bean>
<!-- Replace the label dynamically after getting the configuration properties -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
4.5 Configure Spring to automatically create bean for Mapper interface
MyBatis-Spring provides a converter, MapperScannerConfigurer, to convert the mapping interface to Bean in the Spring container. This allows you to inject the mapped bean into your code
<!-- Create in automatic scan mode Mapper Bean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cnblogs.dao"></property>
</bean>
The basePackage property lets you set the basic package path for the mapper interface file. You can set more than one package path using a semicolon or comma as a delimiter. Each mapper will be recursively searched in the specified package path.
4.6 Configuration Transactions
After combining MyBatis and Spring, Spring AOP is used to manage transactions, while Spring AOP is quite simple, which is divided into declarative transactions and programmatic transactions. Declarative transactions are fine for most scenarios.
Introducing Jar package
compile group: 'org.springframework', name: 'spring-tx', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.10.RELEASE'
<!-- Transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Use declarative transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
5. Complete Spring xml configuration and reference Jar package
The list of Jar introduced
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-tx', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.10.RELEASE'
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.1'
compile group: 'org.mybatis', name: 'mybatis', version: '3.4.5'
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
compile group: 'com.alibaba', name: 'druid', version: '1.1.2'
Spring configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--spring It can be scanned automatically base-pack Below the package or under the subpackage Java file -->
<context:component-scan base-package="com.cnblogs.controller,com.cnblogs.service,com.cnblogs.dao"/>
<!-- Automatic registration RequestMappingHandlerMapping with RequestMappingHandlerAdpter-->
<mvc:annotation-driven/>
<!-- Access to static resource files -->
<mvc:default-servlet-handler/>
<!-- Load the configuration file path -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:properties/datasource.properties"></property>
</bean>
<!-- Replace the label dynamically after getting the configuration properties -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
<!-- Alibaba's database connection pool -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- Basic attributes url , user , password -->
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_user}"/>
<property name="password" value="${jdbc_password}"/>
</bean>
<!-- build SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:config/mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
</bean>
<!-- Create in automatic scan mode Mapper Bean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cnblogs.dao"></property>
</bean>
<!-- Transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Use declarative transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- View parser -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/content"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
conclusion