Spring其实就是一个容器,管理所有注册到其中的bean,并通过IOC机制注入依赖。MyBatis是一个持久层框架,这个框架的作用就是规范Java与数据库的交互。
在MyBatis框架中,与数据库的交互通过如下步骤。
- 读取配置文件mybatis-config.xml。
- 根据配置文件通过SqlSessionFactoryBuilder对象创建sqlSessionFactory对象。
- 调用sqlSessionFactory的openSession()获得sqlSession。
- 调用sqlSession的getMapper()方法并传入接口类型获取这个接口类型的代理对象。
- 通过代理对象去执行该接口的配置文件中的SQL语句。
总结下来,MyBatis框架所必须的文件就是配置文件mybatis-config.xml、与数据库表结构对应的实体bean、接口interface及对应的xml配置文件。
在Spring框架中,基本思想是通过Spring容器直接获得装配好的实体bean。在applicationContext.xml文件中配置相应的实体bean并将依赖注入,然后根据配置文件创建context上下文,由上下文通过传入id和class直接获取实体bean。
Spring和MyBatis整合后,显然不能再通过MyBatis框架中的方式获得sqlSession,那么一个解决方案就是在*Mapper.java中设置一个属性为sqlSession,并在*Mapper.java中通过sqlSession.getMapper()获得代理对象,代理对象执行*Mapper.xml配置的SQL。
可以把mybatis-config.xml中的配置移动到Spring的配置文件中,并在Spring中配置Factory和SqlSession。
又因为接口中不能写方法的具体实现,因此可以通过一个接口的实现类,即*MapperImpl.java,完成上文中提到的解决方案。
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List getUserList() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.getUserList();
}
}
然后再在Spring配置文件中注册这个实现类,并进行sqlSession属性的依赖注入。
这里还有另一种方法,就是继承Spring框架已经编写好的SqlSessionDaoSupport类,这个类中有sqlSession对象,可以通过getSession()方法获得这个对象。这样不需要进行依赖注入。
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
public List getUserList() {
UserMapper mapper = getSession().getMapper(UserMapper.class);
return mapper.getUserList();
}
}
值得注意的是,为了更规范,可以将Spring的配置文件分为spring-dao.xml、spring-mvc.xml、application-context.xml,在application-context.xml中importspring-dao.xml、spring-mvc.xml,并专注配置bean,通过Setter注入将sqlSession注入。
这里的application-context.xml就可以理解为这个Spring容器的特性,在创建context上下文的时候,就导入这个配置文件。



