整合思路
- 需要spring通过单例方式管理SqlSessionFactory
- spring和mabatis整合生成代理对象,使用SqlSessionFactory创建SqlSession(spring和Mybatis整合自动完成)
- 持久层的mapper都需要由spring进行管理
需要spring通过单例方式管理SqlSessionFactory
- 在applicationContext.xml中配置SqlSessionFactory
- SqlSessionFactory在mybaits和spring的整合包下
<!-- sqlSessionFactory -->
<bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
原始dao开发(整合后)
- 加载mybatis的配置文件
<!-- 加载mybaits的配置文件 -->
<property name="configLocation" value = "mybatis/SqlMapConfig.xml"/>
- 连接数据库
<!-- 加载配置文件 -->
<context:property-placeholder location = "classpath:db_properties"/>
<!-- 数据源,使用dbcp -->
<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}" />
</bean>
- 数据源(sqlSessionFactory)
<!-- sqlSessionFactory -->
<bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybaits的配置文件 -->
<property name="configLocation" value = "mybatis/SqlMapConfig.xml"/>
<!-- 数据源 -->
<property name="dataSource" ref = "dataSource"/>
</bean>
mapper.xml
<select id="findUserById" parameterType ="int" resultType="com.shagou.ssm.po.User">
SELECT * FROM USER WHERE id=#{id}
</select>
在SqlMapConfig中加载xml
<!-- 加载映射文件 -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
dao
dao接口实现类需要注入SqlSessionFactory,通过spring进行注入,这里使用Spring声明配置方式,配置dao的bean让UserDaoImpl实现类继承SqlSessionDaoSupport,配置dao
<!-- 原始dao接口 -->
<bean id = "userDao" class = "com.shagou.ssm.dao.UserDaoImpl">
<property name = "sqlSessionFactory" ref = "sqlSessionFactory"></property>
</bean>
UserDaoImpl
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
@Override
public User findUserById(int id) throws Exception {
//继承SqlSessionDaoSupport,通过this.getSqlSession()得到SqlSession
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("test.findUserById",id);
return user;
}
}
dao接口
public interface UserDao {
//根据id查询用户信息
public User findUserById(int id) throws Exception;
}
测试
private ApplicationContext applicationContext;
@Before
public void setUp()throws Exception{
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception {
UserDao userDao = (UserDao)applicationContext.getBean("userDao");
User user = userDao.findUserById(2);
System.out.println(user);
}