MyDao 类具有通过 Hibernate SessionFactory 执行整个持久性任务的方法,它工作得很好。
我在 MyService 中注入了 MyDao,如上所示,但是当在注入 MyDao 后调用 @PostConstruct init() 方法时(调试我可以看到 MyDao 注入得很好),会得到下一个 Hibernate 异常:
org.hibernate.HibernateException:没有找到当前线程的会话
我的服务实施。
@Service("myService")
@Transactional(readOnly = true)
public class MyServiceImpl implements MyService {
@Autowired
private MyDao myDao;
private CacheList cacheList;
@PostConstruct
public void init() {
this.cacheList = new CacheList();
this.cacheList.reloadCache(this.myDao.getAllFromServer());
}
...
}
解决办法
As @Yogi
我认为不允许进行任何交易@PostConstruct
水平如此@Transactional
在这里不会做太多除非mode
被设定为aspectj
in <tx:annotation-driven mode="aspectj" />
.
As per this https://web.archive.org/web/20160217005855/http://forum.spring.io/forum/spring-projects/data/50069-no-transaction-in-transactional-service-called-from-postconstruct您可以使用的讨论TransactionTemplate http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/support/TransactionTemplate.html开始内部手动交易init()
绑定session
但如果您打算严格遵守声明式事务,则需要使用ApplicationListener http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/context/ApplicationListener.html注册事件和用户ContextRefreshedEvent http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/context/event/ContextRefreshedEvent.html发起交易。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)