整合思路
需要spring通过单例的方式管理sqlSessionFactory,
spring和mybaties整合生成代理对象,使用sqlSessionFactory创建sqlSession(spring和mybatis整合自动完成),
持久层的mapper都需要由spring进行管理。
添加jar包:mybatis-spring-1.2.1.jar
配置applicationContext.xml:
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis配置文件 -->
<property name="configLocation" value="/SqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 数据库连接池 使用c3p0-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
</bean>
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
userMapper.xml:
<select id="findUserById" parameterType="int" resultType="mybatis.po.User">
select * from users where id=#{id}
</select>
SqlMapConfig.xml:
<mappers >
<!-- 加载映射文件 -->
<mapper resource="sqlMap/User.xml"></mapper>
</mappers>
dao接口实现类需要注入sqlSessionFactory,通过spring进行注入
dao接口实现类继承SqlSessionDaoSupport
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
@Override
public User findUserById(int id) throws Exception {
//直接使用继承类中的getSqlSession方法
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("test.findUserById", id);
//sqlSession.close();spring方法结束自动关闭释放资源
return user;
}
在applicationContext.xml中配置dao:
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis配置文件 -->
<property name="configLocation" value="/SqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 原始dao接口 -->
<bean id="userDao" class="mybatis.dao.UserDaoImpl">
<!-- 属于父类的属性 -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
测试类:
public class UserDaoImplTest2 {
private ApplicationContext applicationContext;
//setUp方法中得到spring容器,@Before注解 先执行
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
@Test
public void test() throws Exception {
UserMapper userdao = (UserMapper) applicationContext.getBean("userDao");
User user = userdao.findUserById(1);
System.out.println(user);
}
}
Mapper代理开发
applicationContext.xml配置:
<!-- mapper配置
MapperFactoryBean:根据mapper接口生成代理对象-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="mybatis.dao.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>