Spring与MyBatis整合
1. 整合需引入jar包
mybatis-3.1.1.jar
mybatis-spring-1.1.1.jar
2 四种整合方式
2.1 采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!--上面的xsd最好和当前使用的Spring版本号一致,如果换了Spring版本,这个最好也跟着改--> <!-- 引入属性文件 放在最开头,在使用spring之前就引入,里面的变量才能被引用--> <context:property-placeholder location="classpath*:*.properties"/> <!-- 引入属性文件也可以用这种写法 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:config.properties" /> </bean> --> <!-- 自动扫描(需要自动注入的类,对于那些类上有注解:@Repository、@Service、@Controller、@Component都进行注入) --> <!--因为 Spring MVC 是 Spring 的子容器,所以我们在 Spring MVC 的配置中再指定扫描 Controller 的注解,这里是父容器的配置地方--> <!--注解注入的相关材料可以看:--> <!--http://blog.csdn.net/u012763117/article/details/17253849--> <!--http://casheen.iteye.com/blog/295348--> <!--http://blog.csdn.net/zhang854429783/article/details/6785574--> <context:component-scan base-package="com.dhm"> <context:exclude-filter type="regex" expression=".*\.controller\..*" /> </context:component-scan> <!-- 声明式事务相关配置--> <tx:annotation-driven transaction-manager="txManager"/> <!-- mysql --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true"> <property name="url"> <value>jdbc:mysql://localhost:3306/test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描 mapper.xml文件(读取的是编译出来的classes目录下的module目录下的具体模块的mapping目录下的任意xml文件) --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> <!--最新mybatis的配置文件位置--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- mapper 接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.dhm.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </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" > <!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀) --> <mapper namespace="com.dhm.mapper.UserMapper" > <!--在select标签中编写查询的SQL语句, parameterType为String类型单个参数,mybatis对应的内置对象_parameter --> <select id="getUserByUserId" parameterType="java.lang.String" resultType="java.util.HashMap"> select user_name,dept_id,is_valid from user where <if test="_parameter != null"> user_id=${_parameter} </if> </select> </mapper>
UserMapper(相当于dao类)
package com.dhm.mapper; import java.util.Map; /** * MapperScanner扫描到后会自动生成代理对象。 * 注意,接口中的方法名称要和对应的MyBatis映射文件中的语句的id值一样,因为生成的 * 动态代理,会根据这个匹配相应的Sql语句执行。另外就是方法的参数和返回值也需要注 * 意,接口中的方法如何定义,对应的MyBatis映射文件就应该进行相应的定义。 */ public interface UserMapper { Map getUserByUserId(String id); }
service类
package com.dhm.service.impl; import com.dhm.mapper.UserMapper; import com.dhm.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Map; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; public Map getUserByUserId(String id) { return userMapper.getUserByUserId(id); } }
2.2 采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。SqlSessionFactoryBean有一个必须属性dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!--上面的xsd最好和当前使用的Spring版本号一致,如果换了Spring版本,这个最好也跟着改--> <!-- 引入属性文件 放在最开头,在使用spring之前就引入,里面的变量才能被引用--> <context:property-placeholder location="classpath*:*.properties"/> <!-- 引入属性文件也可以用这种写法 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:config.properties" /> </bean> --> <!-- 自动扫描(需要自动注入的类,对于那些类上有注解:@Repository、@Service、@Controller、@Component都进行注入) --> <!--因为 Spring MVC 是 Spring 的子容器,所以我们在 Spring MVC 的配置中再指定扫描 Controller 的注解,这里是父容器的配置地方--> <!--注解注入的相关材料可以看:--> <!--http://blog.csdn.net/u012763117/article/details/17253849--> <!--http://casheen.iteye.com/blog/295348--> <!--http://blog.csdn.net/zhang854429783/article/details/6785574--> <context:component-scan base-package="com.dhm"> <context:exclude-filter type="regex" expression=".*\.controller\..*" /> </context:component-scan> <!-- 声明式事务相关配置--> <tx:annotation-driven transaction-manager="txManager"/> <!-- mysql --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true"> <property name="url"> <value>jdbc:mysql://localhost:3306/test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描 dao.xml文件(读取的是编译出来的classes目录下的module目录下的具体模块的mapping目录下的任意xml文件) --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> <!--最新mybatis的配置文件位置--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- mybatis spring sqlSessionTemplate,使用时直接让spring注入即可 --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg> </bean> </beans>
UserDao.java
package com.dhm.dao; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.Map; @Repository public class UserDao { @Resource private SqlSessionTemplate sqlSessionTemplate; public Map getUserByUserId(String id) { return sqlSessionTemplate.selectOne("getUserByUserId", id); } }
service类
package com.dhm.service.impl; import com.dhm.dao.UserDao; import com.dhm.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Map; @Service public class UserServiceImpl implements UserService { @Resource private UserDao userMapper; public Map getUserByUserId(String id) { return userMapper.getUserByUserId(id); } }
2.3 采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!--上面的xsd最好和当前使用的Spring版本号一致,如果换了Spring版本,这个最好也跟着改--> <!-- 引入属性文件 放在最开头,在使用spring之前就引入,里面的变量才能被引用--> <context:property-placeholder location="classpath*:*.properties"/> <!-- 引入属性文件也可以用这种写法 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:config.properties" /> </bean> --> <!-- 自动扫描(需要自动注入的类,对于那些类上有注解:@Repository、@Service、@Controller、@Component都进行注入) --> <!--因为 Spring MVC 是 Spring 的子容器,所以我们在 Spring MVC 的配置中再指定扫描 Controller 的注解,这里是父容器的配置地方--> <!--注解注入的相关材料可以看:--> <!--http://blog.csdn.net/u012763117/article/details/17253849--> <!--http://casheen.iteye.com/blog/295348--> <!--http://blog.csdn.net/zhang854429783/article/details/6785574--> <context:component-scan base-package="com.dhm"> <context:exclude-filter type="regex" expression=".*\.controller\..*" /> </context:component-scan> <!-- 声明式事务相关配置--> <tx:annotation-driven transaction-manager="txManager"/> <!-- mysql --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true"> <property name="url"> <value>jdbc:mysql://localhost:3306/test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描 dao.xml文件(读取的是编译出来的classes目录下的module目录下的具体模块的mapping目录下的任意xml文件) --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> <!--最新mybatis的配置文件位置--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> </beans>
userDao.java
package com.dhm.dao; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.Map; @Repository public class UserDao extends SqlSessionDaoSupport { /**使用SqlSessionDaoSupport必须注意,此处源码1.1.1中有自动注入,1.2中取消了自动注入,需要手工注入,侵入性强 也可在spring-mybatis.xml中如下配置,但是这种有多少个dao就要配置到少个,多个dao就很麻烦。 <bean id="userDao" class="com.hua.saf.dao.UserDao"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> */ @Resource public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } public Map getUserByUserId(String id) { return getSqlSession().selectOne("getUserByUserId", id); } }
2.4 单个的MapperFactoryBean,一个mapper对应一个MapperFactoryBean对象
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!--上面的xsd最好和当前使用的Spring版本号一致,如果换了Spring版本,这个最好也跟着改--> <!-- 引入属性文件 放在最开头,在使用spring之前就引入,里面的变量才能被引用--> <context:property-placeholder location="classpath*:*.properties"/> <!-- 引入属性文件也可以用这种写法 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:config.properties" /> </bean> --> <!-- 自动扫描(需要自动注入的类,对于那些类上有注解:@Repository、@Service、@Controller、@Component都进行注入) --> <!--因为 Spring MVC 是 Spring 的子容器,所以我们在 Spring MVC 的配置中再指定扫描 Controller 的注解,这里是父容器的配置地方--> <!--注解注入的相关材料可以看:--> <!--http://blog.csdn.net/u012763117/article/details/17253849--> <!--http://casheen.iteye.com/blog/295348--> <!--http://blog.csdn.net/zhang854429783/article/details/6785574--> <context:component-scan base-package="com.dhm"> <context:exclude-filter type="regex" expression=".*\.controller\..*" /> </context:component-scan> <!-- 声明式事务相关配置--> <tx:annotation-driven transaction-manager="txManager"/> <!-- mysql --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true"> <property name="url"> <value>jdbc:mysql://localhost:3306/test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描 mapper.xml文件(读取的是编译出来的classes目录下的module目录下的具体模块的mapping目录下的任意xml文件) --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> <!--最新mybatis的配置文件位置--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.dhm.mapper.UserMapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </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" > <!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀) --> <mapper namespace="com.dhm.mapper.UserMapper" > <!-- 在select标签中编写查询的SQL语句, parameterType为String类型单个参数,mybatis对应的内置对象_parameter --> <select id="getUserByUserId" parameterType="java.lang.String" resultType="java.util.HashMap"> select user_name,dept_id,is_valid from user where <if test="_parameter != null"> user_id=${_parameter} </if> </select> </mapper>
UserMapper.java
package com.dhm.mapper; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.Map; public interface UserMapper { Map getUserByUserId(String id); }
service类
package com.dhm.service.impl; import com.dhm.mapper.UserMapper; import com.dhm.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Map; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; public Map getUserByUserId(String id) { return userMapper.getUserByUserId(id); } }