要整合Spring跟Mybatis那就必须导入Spring的包,Mybatis的包,Mybatis-Spring的整合包,以及连接数据库所需要的包
,
单独使用Mybatis时,我们需要在Mybatis核心配置文件(sqlMapConfig,xml)中配置连接数据池,各个映射文件,然后再由这些配置文件作为"原材料"创建一个SqlSessionFactory
SqlSessionFactory再根据我们传入的接口,生成一个动态代理对象
现在这些事不需要Mybatis来做了,全部交给Spring,来到Spring的核心配置文件applicationContext.xml
我们可以看到原先在Mybatis中配置的数据池,现在也交由Spring来配置,然后再把数据吃和核心配置文件一起放到工厂bean中,去创建一个工厂。再将工厂bean和接口一起放入动态代理bean,便能够创建一个动态动态代理对象(有人会问为什么看不到工厂的bean,那是因为工厂bean已经交由spring管理了,动态代理bean能够去spring找到这个工厂,所以不需要我们去添加)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" />
<!--1.讲连接池放入spring容器 -->
<bean name="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="url" value="${jdbc.jdbcUrl}"></property>
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="Password" value="${jdbc.password}"></property>
</bean>
<!-- Mybatis的工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 核心配置文件的位置 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<!-- Mapper动态代理开发 扫描 自己会去找Spring找工厂-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 基本包 -->
<property name="basePackage" value="mapper"></property>
</bean>
</beans>
整合后,我们就可以直接去跟spring要动态代理对象,来进行数据库操作了,而不再像从前一样,每次要用就得创建工厂,创建 代理对象十分麻烦
package Test;
import java.util.List;
import org.junit.Test;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mapper.UsersMapper;
import pojo.Users;
import pojo.UsersExample;
public class test {
@Test
public void testMapper(){
ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UsersMapper bean = ApplicationContext.getBean(UsersMapper.class);
}
}