@PostConstruct中没有会话休眠 [英] No Session Hibernate in @PostConstruct
问题描述
MyDao类具有通过Hibernate SessionFactory执行全部持久性任务的方法,它工作正常.
MyDao class have the methods to do whole persistence tasks through Hibernate SessionFactory, it works fine.
如上所述,我在MyService中注入了MyDao,但是在注入MyDao之后(通过调试可以看到MyDao注入)调用@PostConstruct init()方法时,会得到下一个Hibernate异常:
I inject MyDao in MyService as can see above, but when @PostConstruct init() method is called after injected MyDao (debugging I can see MyDao well injected) get the next Hibernate exception:
org.hibernate.HibernateException:未找到当前线程的会话
org.hibernate.HibernateException: No Session found for current thread
我的服务实施.
@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());
}
...
}
解决方法
按照我上面推荐的 @ Yogi ,我使用TransactionTemplate来获得一个有效/活动的交易会话,在这种情况下,我已经实现了整个构造函数,并且对我.
As @Yogi recommended above to me, I have used TransactionTemplate to get one valid/active transaction session, in this case I have implemented throught constructor and works fine for me.
@Service("myService")
@Transactional(readOnly = true)
public class MyServiceImpl implements MyService {
@Autowired
private MyDao myDao;
private CacheList cacheList;
@Autowired
public void MyServiceImpl(PlatformTransactionManager transactionManager) {
this.cacheList = (CacheList) new TransactionTemplate(transactionManager).execute(new TransactionCallback(){
@Override
public Object doInTransaction(TransactionStatus transactionStatus) {
CacheList cacheList = new CacheList();
cacheList.reloadCache(MyServiceImpl.this.myDao.getAllFromServer());
return cacheList;
}
});
}
...
}
推荐答案
我认为 @PostConstruct
级别上不允许进行任何交易,因此 @Transactional
除非在 <tx:annotation-driven mode="aspectj" />
中将mode
设置为aspectj
,否则此处不会做很多事情.
I don't think there is any transaction allowed on @PostConstruct
level so @Transactional
won't do much here unless mode
is set to aspectj
in <tx:annotation-driven mode="aspectj" />
.
根据 TransactionTemplate
开始在init()
内进行手动交易以绑定session
,但是如果您要严格遵守声明式事务,您需要使用
As per this discussion you can use TransactionTemplate
to start manual transaction inside init()
to bind session
but if you intend to strictly adhere to declarative transaction you need to use ApplicationListener
to register event and user ContextRefreshedEvent
to initiate transaction.
这篇关于@PostConstruct中没有会话休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!