Spring整合Mybatis(二)
SqlSession创建的第二种方式
通过mapper的实现类继承SqlSessionDaoSupport,但是applacationContext文件中要注入的属性就要从sqlSessionTemplate变成sqlSessionFactory
package com.psy.dao;
import com.psy.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class UserDaoImpl2 extends SqlSessionDaoSupport implements UserDao {
@Override
public User queryUserById(Integer id) {
SqlSession sqlSession = getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
return mapper.queryUserById(id);
}
}
@Test
public void test2() {
ClassPathXmlApplicationContext cp = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = cp.getBean("userDao", UserDao.class);
System.out.println(userDao.queryUserById(1));
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--相当于学习Mybatis时候加的那个工具类,这里只是吧工具类变成了xml的形式-->
<import resource="spring-dao.xml"/>
<!--扫描dao接口-->
<bean id="userDao" class="com.psy.dao.UserDaoImpl2">
<property name="sqlSessionFactory" ref="sqSessionFactory"/>
</bean>
</beans>