spring-mybatis整合
spring-mybatis整合
需要导入的包
junit
lombok(可选)
mybatis-spring
spring-webmvc
aspectjweaver
mysql-connector-java
mybatis
spring-jdbc
整合方法一
pojo类+mapper+mapper.xml不变
添加一个接口实现类,私有化sqlSessionTemplate
public class StudentMapperImpl implements StudentMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List getStudent() {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
return mapper.getStudent();
}
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
测试类
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentMapper studentMapper = context.getBean("StudentMapper", StudentMapper.class);
List students = studentMapper.getStudent();
for (Student student : students) {
System.out.println(student);
}
}
整合方式二
在原来的基础上修改接口实现类和applicationContext.xml中注册它的配置
public class StudentMapperImpl extends SqlSessionDaoSupport implements StudentMapper{
public List getStudent() {
return getSqlSession().getMapper(StudentMapper.class).getStudent();
}
}
spring-dao.xml可以去除掉
dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate.
SqlSessionDaoSupport是对SqlSessionTemplate的处理,需要的是sqlSessionFactory,因此可以去掉sqlSession的相关配置。