我们先来对比一下,不使用mybatis的API跟使用mybatis的API的区别!
1、不使用 mybatisAPI:(方式1:使用SqlSessionDaoSupport类,无需在配置文件中配置)在前面的博文中也讲到了: 博文链接
package com.dao.impl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.dao.ManagerMapper;
import com.models.Manager;
public class ManagerMapperImpl extends SqlSessionDaoSupport implements ManagerMapper{
@Override
public Manager getManager(String managerID) {
return (Manager)getSqlSession().selectOne("com.dao.ManagerMapper.getManager", managerID);
}
}
方式2:需要在配置文件中配置class="org.mybatis.spring.SqlSessionTemplate"
2、使用mybatisAPI:public class UserMapperImpl implements UserMapper{
private SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public User getUser(String userID) {
return (User)sqlSession.selectOne("com.dao.UserMapper.getUser", userID);
}}
package com.dao.impl;上面的代码是不是和单独使用mybatis的时候很类似?确实是这样的。只是这里是利用spring容器来完成注入的。
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.dao.ManagerMapper;
import com.models.Manager;
public class ManagerMapperImpl implements ManagerMapper{
private SqlSessionFactory sqlSessionFactory;
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public Manager getManager(String managerID) {
return (Manager)sqlSessionFactory.openSession().selectOne("com.dao.ManagerMapper.getManager", managerID);
}
}
所以,我们的applicationContext配置文件应该 修改id = managerMapperImpl的bean,目的只是依赖注入,也就是实例化factory对象
我们测试一下。测试代码前面的一样<bean id="managerMapperImpl" class="com.dao.impl.ManagerMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
跑起来了吗? = =ManagerMapperImpl managerMapperImpl = context.getBean(ManagerMapperImpl.class);
Manager manager = managerMapperImpl.getManager("1");
System.out.println("manager info = "+manager.getId()+"; "+manager.getName()+"; "+manager.getPassword());