赞
踩
原因是mybatis-spring-1.2.0版本SqlSessionDaoSupport
取消了自动注入SqlSessionFactory
和 SqlSessionTemplate
/** * Convenient super class for MyBatis SqlSession data access objects. * It gives you access to the template which can then be used to execute SQL methods. * <p> * This class needs a SqlSessionTemplate or a SqlSessionFactory. * If both are set the SqlSessionFactory will be ignored. * <p> * {code Autowired} was removed from setSqlSessionTemplate and setSqlSessionFactory * in version 1.2.0. * * @see #setSqlSessionFactory * @see #setSqlSessionTemplate * @see SqlSessionTemplate * @version $Id$ */ public abstract class SqlSessionDaoSupport extends DaoSupport { private SqlSession sqlSession; private boolean externalSqlSession; public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { if (!this.externalSqlSession) { this.sqlSession = new SqlSessionTemplate(sqlSessionFactory); } } public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSession = sqlSessionTemplate; this.externalSqlSession = true; } ……
1.1.1中的代码为:
public abstract class SqlSessionDaoSupport extends DaoSupport { private SqlSession sqlSession; private boolean externalSqlSession; @Autowired(required = false) public final void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { if (!this.externalSqlSession) { this.sqlSession = new SqlSessionTemplate(sqlSessionFactory); } } @Autowired(required = false) public final void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSession = sqlSessionTemplate; this.externalSqlSession = true; } …… }
解决方案:
创建一个Dao,继承SqlSessionDaoSupport,重写setSqlSessionFactory的方法。
public class AbstractDao extends SqlSessionDaoSupport {
@Override
@Autowired
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
@Override
@Autowired
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
super.setSqlSessionTemplate(sqlSessionTemplate);
}
}
为什么要在高版本去掉自动注入呢?
因为在框架层面不能断定应用的SqlSessionFactory只有一个。具体可以参考:https://stackoverflow.com/questions/17494238/autowiring-in-mybatis-spring-1-2-0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。