gpt4 book ai didi

spring - @PostConstruct 中没有 session hibernate

转载 作者:行者123 更新时间:2023-12-02 11:50:24 33 4
gpt4 key购买 nike

MyDao 类具有通过 Hibernate SessionFactory 完成整个持久性任务的方法,它工作得很好。

我在 MyService 中注入(inject)了 MyDao,如上所示,但是当注入(inject) MyDao 后调用 @PostConstruct init() 方法时(调试我可以看到 MyDao 很好地注入(inject))得到下一个 Hibernate 异常:

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 来获取一个有效/事件的交易 session ,在这种情况下,我已经通过构造函数实现了并且可以很好地工作我。

@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 在这里不会做太多事情,除非 mode设置为aspectj <tx:annotation-driven mode="aspectj" />

根据this您可以使用 TransactionTemplate 进行讨论在init()内开始手动交易绑定(bind)session但如果您打算严格遵守声明式事务,则需要使用 ApplicationListener 注册事件和用户 ContextRefreshedEvent 发起交易。

关于spring - @PostConstruct 中没有 session hibernate ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22193562/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com