spring和mybatis整合动态代理开发
在Mybatis动态代理开发的基础之上结合spring
Mybatis部分:
- SqlMapConfig.xml : 加载mapper映射文件
- mapper包下(mapper接口,mapper映射文件):sql语句
- pojo类 :数据库表的属性一 一对应
- lo4j.properties、jdbc.properties
Spring部分:
applicationContext.xml : 注入mybatis工厂,注入mapper动态代理开发的工厂bean
- jdbc.properties
- 数据库连接池
- Mybatis工厂:相当于这部分代码
String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
- mapper动态代理开发:相当于这部分代码:只不过缺sqlSessionFactory和mapper接口,所以注入
SqlSession sqlSession = sqlSessionFactory.openSession(true); usermapper mapper = sqlSession.getMapper(usermapper.class);
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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--加载jdbc.properties-->
<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}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!--Mybatis工厂-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactoryBean">
<!--本来配置数据库是SqlMapConfig.xml的事情,但是spring来了,就交给spring,所以这里要注入一下-->
<property name="dataSource" ref="dataSource"/>
<!--加载MYbatis核心文件-->
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
</bean>
<!--mapper动态代理开发-->
<bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="mapperFactoryBean">
<!--将mybatis创建好的工厂拿来创建sqlsession-->
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
<!--给一个mapper接口,创建接口的实现类-->
<property name="mapperInterface" value="com.mybatis.mapper.usermapper"/>
</bean>
</beans>
测试类:
@Test
public void test23(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
usermapper mapper = (usermapper) applicationContext.getBean("mapperFactoryBean");
也可以直接写接口.class
usermapper mapper = applicationContext.getBean(usermapper.class);
User user = mapper.find(1);
System.out.println(user);
}