Three integration methods of spring and mybatis
- 2020-06-23 00:26:24
- OfStack
1. With MapperScannerConfigurer, it will find the mapper under the classpath and automatically create them as MapperFactoryBean.
spring-mybatis.xml:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- Automatic scanning -->
<context:component-scan base-package="com.hua.saf" />
<!-- Import configuration file -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- Initializes the connection size -->
<property name="initialSize" value="${initialSize}" />
<!-- Maximum number of connection pools -->
<property name="maxActive" value="${maxActive}" />
<!-- Maximum free connection pool -->
<property name="maxIdle" value="${maxIdle}" />
<!-- Minimum idle connection pool -->
<property name="minIdle" value="${minIdle}" />
<!-- Gets the maximum wait time for a connection -->
<property name="maxWait" value="${maxWait}" />
</bean>
<!-- spring and MyBatis Perfect integration, no need mybatis Configuration mapping file -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- Automatic scanning mapping.xml File, ** Represents iterative lookup -->
<property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
</bean>
<!-- DAO The package name of the interface, Spring The class under it is automatically looked up , The classes under the package need to be used @MapperScan annotations , Otherwise container injection will fail -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hua.saf.*" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- ( Transaction management )transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- For this mapper The specified 1 A wei 1 the namespace . namespace Is customarily set to the package name +sql Map the file name, so that you can be assured namespace The value is only 1 the
For example, namespace="me.gacl.mapping.userMapper" is me.gacl.mapping( The package name )+userMapper(userMapper.xml File removal suffix )
-->
<mapper namespace="com.hua.saf.dao.UserDao">
<!--
in select Write the query in the tag SQL Statements, Set up the select Of the label id Properties for getUser . id The attribute value must be unique 1 Can not be repeated ,
use parameterType Property indicates the type of parameter to use in the query, resultType Property indicates the type of result set returned by the query
resultType="com.hua.saf.User" Encapsulate the result of the query 1 a User Class object ,User Class is t_user The entity class corresponding to the table
-->
<!-- According to the id query 1 a user object -->
<select id="getUser" parameterType="int" resultType="com.hua.saf.pojo.User">
select * from t_user where id=#{id}
</select>
</mapper>
dao class:
/**
* Here, @MapperScan That's what I said above Mapper The required configuration in the scanner generates the proxy object automatically.
* Note that the method name in the interface corresponds to the MyBatis Of a statement in a mapping file id value 1 Student: Like, because it's generated
* The dynamic proxy will match the corresponding one based on this Sql Statement execution. The other thing is that method parameters and return values also need to be noted
* Meaning. How are the methods in the interface defined MyBatis The mapping file should be defined accordingly.
* Finally, in the annotation userDao Is used as a Spring the Bean the id( or name) It is convenient for me to use
* In the Service Layer for injection use.
*/
@MapperScan
public interface UserDao {
// The method name here must be and mapper In the mapping file id The same name
// Go back to map the file through com.hua.saf.dao.UserDao.getUser, namely this.getClass().getName()+".getUser"
public User getUser(int id);
}
service class
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private UserDao userDao;
public User getUser(int id) {
return userDao.getUser(id);
}
}
2, using interface org. apache. ibatis. session. SqlSession implementation class org. mybatis. spring. SqlSessionTemplate.
In mybatis, sessionFactory can be created by SqlSessionFactoryBuilder. In ES35en-ES36en, SqlSessionFactoryBean is used instead. SqlSessionFactoryBean has one required attribute, dataSource, and one common attribute, configLocation, which specifies the xml configuration file path for mybatis.
spring-mybatis.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- Automatic scanning -->
<context:component-scan base-package="com.hua.saf" />
<!-- Import configuration file -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- Initializes the connection size -->
<property name="initialSize" value="${initialSize}" />
<!-- Maximum number of connection pools -->
<property name="maxActive" value="${maxActive}" />
<!-- Maximum free connection pool -->
<property name="maxIdle" value="${maxIdle}" />
<!-- Minimum idle connection pool -->
<property name="minIdle" value="${minIdle}" />
<!-- Gets the maximum wait time for a connection -->
<property name="maxWait" value="${maxWait}" />
</bean>
<!-- spring and MyBatis Perfect integration, no need mybatis Configuration mapping file -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
<!-- Automatic scanning mapping.xml File, ** Represents iterative lookup , Can also be used in sqlMapConfig.xml Separately specified in xml file -->
<property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
</bean>
<!-- mybatis spring sqlSessionTemplate, When used, simply let spring Injection can -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
<!-- ( Transaction management )transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC
"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.hua.saf.pojo.User" alias="User" />
</typeAliases>
</configuration>
User.java
public class User {
private int id;
private String username;
private String password;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
UserDao.java
@Repository
public class UserDao{
@Resource
private SqlSessionTemplate sqlSessionTemplate;
public User getUser(int id) {
return sqlSessionTemplate.selectOne(this.getClass().getName() + ".getUser", 1);
}
}
UserService.java
@Service
public class UserService{
@Resource
private UserDao userDao;
public User getUser(int id) {
return userDao.getUser(id);
}
}
3, using an abstract class org. mybatis. spring. support. Provide SqlSession SqlSessionDaoSupport.
spring-mybatis.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- Automatic scanning -->
<context:component-scan base-package="com.hua.saf" />
<!-- Import configuration file -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- Initializes the connection size -->
<property name="initialSize" value="${initialSize}" />
<!-- Maximum number of connection pools -->
<property name="maxActive" value="${maxActive}" />
<!-- Maximum free connection pool -->
<property name="maxIdle" value="${maxIdle}" />
<!-- Minimum idle connection pool -->
<property name="minIdle" value="${minIdle}" />
<!-- Gets the maximum wait time for a connection -->
<property name="maxWait" value="${maxWait}" />
</bean>
<!-- spring and MyBatis Perfect integration, no need mybatis Configuration mapping file -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
<!-- Automatic scanning mapping.xml File, ** Represents iterative lookup , Can also be used in sqlMapConfig.xml Separately specified in xml file -->
<property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
</bean>
<!-- ( Transaction management )transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- For this mapper The specified 1 A wei 1 the namespace . namespace Is customarily set to the package name +sql Map the file name, so that you can be assured namespace The value is only 1 the
For example, namespace="me.gacl.mapping.userMapper" is me.gacl.mapping( The package name )+userMapper(userMapper.xml File removal suffix )
-->
<mapper namespace="com.hua.saf.dao.UserDao">
<!--
in select Write the query in the tag SQL Statements, Set up the select Of the label id Properties for getUser . id The attribute value must be unique 1 Can not be repeated ,
use parameterType Property indicates the type of parameter to use in the query, resultType Property indicates the type of result set returned by the query
resultType="com.hua.saf.User" Encapsulate the result of the query 1 a User Class object ,User Class is t_user The entity class corresponding to the table
-->
<!-- According to the id query 1 a user object -->
<select id="getUser" parameterType="int" resultType="com.hua.saf.pojo.User">
select * from t_user where id=#{id}
</select>
</mapper>
0
User.java
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- For this mapper The specified 1 A wei 1 the namespace . namespace Is customarily set to the package name +sql Map the file name, so that you can be assured namespace The value is only 1 the
For example, namespace="me.gacl.mapping.userMapper" is me.gacl.mapping( The package name )+userMapper(userMapper.xml File removal suffix )
-->
<mapper namespace="com.hua.saf.dao.UserDao">
<!--
in select Write the query in the tag SQL Statements, Set up the select Of the label id Properties for getUser . id The attribute value must be unique 1 Can not be repeated ,
use parameterType Property indicates the type of parameter to use in the query, resultType Property indicates the type of result set returned by the query
resultType="com.hua.saf.User" Encapsulate the result of the query 1 a User Class object ,User Class is t_user The entity class corresponding to the table
-->
<!-- According to the id query 1 a user object -->
<select id="getUser" parameterType="int" resultType="com.hua.saf.pojo.User">
select * from t_user where id=#{id}
</select>
</mapper>
1
UserDao.java
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- For this mapper The specified 1 A wei 1 the namespace . namespace Is customarily set to the package name +sql Map the file name, so that you can be assured namespace The value is only 1 the
For example, namespace="me.gacl.mapping.userMapper" is me.gacl.mapping( The package name )+userMapper(userMapper.xml File removal suffix )
-->
<mapper namespace="com.hua.saf.dao.UserDao">
<!--
in select Write the query in the tag SQL Statements, Set up the select Of the label id Properties for getUser . id The attribute value must be unique 1 Can not be repeated ,
use parameterType Property indicates the type of parameter to use in the query, resultType Property indicates the type of result set returned by the query
resultType="com.hua.saf.User" Encapsulate the result of the query 1 a User Class object ,User Class is t_user The entity class corresponding to the table
-->
<!-- According to the id query 1 a user object -->
<select id="getUser" parameterType="int" resultType="com.hua.saf.pojo.User">
select * from t_user where id=#{id}
</select>
</mapper>
2
UserService.java
@Service
public class UserService{
@Resource
private UserDao userDao;
public User getUserss(int id) {
return userDao.getUser(1);
}
}