回顾mybatis: 创建mybatis的全局配置文件,配置数据源信息,配置映射 通过读取mybatis的全局配置文件创建sqlSessionFactory实例(会话工厂只需要创建一份就可以了) 通过会话工厂创建会话,SQLSession
整合思想: Spring通过单例方式管理SQLSessionFactory spring和mybatis整合生成代理对象,使用SQLSessionFactory创建SQLSession,整合自动完成 持久层的Mapper都需要交给Spring管理
在mybatis中,SQLSessionFactory由SQLSessionFactoryBuilder来创建 在mybatis和spring整合过程中,使用SQLSessionFactoryBean来替代,SQLSessionFactoryBean有一个必须的属性DataSource,另外需要一个通用的属性configLocation(用来指定mybatis的xml配置文件)
第一步:引入spring-mybatis的整合jar包 引入spring的依赖,引入mybatis的依赖 还需要mybatis提供的一个专门整合spring的jar包:mybatis-spring
<!--mybatis和spring整合jar--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>第二步:创建bean类,mapper.xml和mapper.java文件 省略 注意:mybatis的全局配置文件中的数据源以及mapper映射放入到spring中
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--数据源 在spring整合后,将数据源放在spring的配置文件中--> <!--<environments default="">--> <!--<environment id="">--> <!--<transactionManager type=""></transactionManager>--> <!--<dataSource type=""></dataSource>--> <!--</environment>--> <!--</environments>--> <!--mapper 在和spring整合后,可以放在spring配置文件中--> <!--<mappers>--> <!--<mapper resource=""/>--> <!--</mappers>--> </configuration>第三步:整合SQLSessionFactory创建
<?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" 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"> <bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource"> <!--配置连接数据库的核心配置4个参数--> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="user" value="root"/> <property name="password" value="123456"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis"/> </bean> <!--配置SQLSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--配置数据源--> <property name="dataSource" ref="dataSource"/> <!--加载mybatis的配置--> <property name="configLocation" value="mybatis/mybatis.xml"/> <!--配置xml文件的映射,在mybatis当中,在<mapper>标签下添加的--> <property name="mapperLocations"> <list> <value>mapper/User2Mapper.xml</value> </list> </property> </bean> </beans>第四步:通过代理对象操作
<!-- 通过代理对象进行mapper的映射 class即mybatis-spring包提供的MapperFactoryBean --> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!--mapperInterface指定mapper接口--> <property name="mapperInterface" value="com.tulun.dao.User2Mapper"/> <!--指定SQLSessionFactory--> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>