只使用mybatis时,我们发现每次使用mapper接口操作数据都很麻烦,并且程序耦合度高,为了解决这个问题,可以使用spring框架与mybatis框架进行整合。将一些需要的对象交给spring容器来配置和创建。
导入相应的整合包后,首先将数据库的配置交给spring配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据源,使用dbcp -->
<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}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
使用mapper代理开发时,在spring容器中配置mapper的接口生成代理对象:
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
//mapperInterface指定mapper接口
<property name="mapperInterface" value="com.iot.ssm.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
通过MapperScannerConfigurer进行mapper扫描可以实现批量配置:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名
如果扫描多个包,每个包中间使用半角逗号分隔
-->
<property name="basePackage" value="com.iot.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
这样,要使用mapper时,只需要通过注解的方式:
@Autowired
private UserMapper userMapper;
或加载spring配置文件的方式(Test方法里使用):
private ApplicationContext applicationContext;
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserMapper userMapper = (UserMapper)applicationContext.getBean("userMapper");