Mybatis与Spring集成
为什么需要集成
因为目前很多企业都是基于spring框架开发的,所以将mybatis交给spring管理显得就合情合理了。并且利用spring的声明式事物和aop技术可以很好的管理sqlSession的打开与关闭。
集成思路
MyBatis的核心是围绕一个SqlSessionFactory对象的,所以要定义一个这样的Bean对象,还需要定义一个DataSourceTransactionManager数据源事物管理器Bean让Spring管理SqlSession会话事务。创建SqlSessionFactory需要引用数据源,因此需要定义一个数据源对象。
application-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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- 开启Spring自动扫描功能 -->
<context:component-scan base-package="com.xuyi" />
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 一系列数据源配置... -->
</bean>
<!-- 配置SqlSessionFactory对象bean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 如果使用的是Mapper接口方式,在下面的MapperScannerConfigurer bean里配置,这里可以不用配置了 -->
<!-- <property name="configLocation" value="classpath:mybatis-config.xml"></property> -->
</bean>
<!-- 配置数据源事务管理器bean -->
<bean
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置自动扫描Mapper接口,指定basePackage -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xuyi.springmybatis.mybatisspring.dao"></property>
</bean>
</beans>
appMain代码
//指定其以SpringJUnit4ClassRunner运行
@RunWith(SpringJUnit4ClassRunner.class)
//指定其读取配置文件
@ContextConfiguration(value={"/applicationContext.xml"})
public class AppTest {
//自动注入StudentMapper
@Autowired
private StudentMapper studentMapper;
@Test
public void testHello() {
Student student = studentMapper.selectStudentById(4);
}
}
备注:通过以上配置之后就可以在需要的地方直接注入Mapper接口就可以直接使用Mapper的代理对象了。
参考
http://www.mybatis.org/spring/
http://www.codingpedia.org/ama/spring-mybatis-integration-example/
http://www.cnblogs.com/xdp-gacl/p/4002804.html