【spring笔记】Spring整合Mybaties
1、实现方式1
核心思想:利用Spring配置依赖注入创建sqlSessionFactory和sqlSession实例
- 需要的包如下:
1.1、编写数据源
这个很简单,就是spring在包装了一下配置参数
1.2、创建sqlSessionFactory
对比Mybatis就是不用自己new对象了,框架都写好了,用配置问价注入容器
1.3、创建sqlSessionTemplate
其实就是创建一个sqlSession
1.4、给接口加实现类
为什么这里需要实现类呢?因为Mybatis不能自动生成类对象,所以需要我们手动写一个实现类,然后将上面的sqlSessioinTemplate注入进去
package com.wcy.mapper;
import com.wcy.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class StudentMapperImpl implements StudentMapper {
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<Student> getStudentList() {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.getStudentList();
}
}
1.5、将自己写的实现类,注入到Spring中
1.6、测试
public class MyTest_spring_Mybatis {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
StudentMapper studentMapper = context.getBean("studentMapper", StudentMapper.class);
for(Student student : studentMapper.getStudentList()) {
System.out.println(student.toString());
}
}
}
测试过程还发现一个问题
java.lang.NoSuchMethodError: org.springframework.beans.factory.config.BeanDefinition.get ResolvableType()Lorg/springframework/core/ResolvableType;
最后发现是springweb-mvc和sping-jdbc版本不一致导致的,统一就好了
2、实现方式2
方式二其实就是,sqlSession通过spring提供的类直接get出来
官网描述如下:
2.1、实现接口的类
package com.wcy.mapper;
import com.wcy.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class StudentMapperImpl2 extends SqlSessionDaoSupport implements StudentMapper{
@Override
public List<Student> getStudentList() {
return getSqlSession().getMapper(StudentMapper.class).getStudentList();
}
}
配置参数里,因为是继承了SqlSessionDaoSupport类,所以直接注入sqlSessionFactory就好了
SqlSessionDaoSupport源码:
package org.mybatis.spring.support;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.DaoSupport;
import org.springframework.util.Assert;
public abstract class SqlSessionDaoSupport extends DaoSupport {
private SqlSessionTemplate sqlSessionTemplate;
public SqlSessionDaoSupport() {
}
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
if (this.sqlSessionTemplate == null || sqlSessionFactory != this.sqlSessionTemplate.getSqlSessionFactory()) {
this.sqlSessionTemplate = this.createSqlSessionTemplate(sqlSessionFactory);
}
}
}
<bean id="studentMapper2" class="com.wcy.mapper.StudentMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>