[英]Store List of Objects in Session Scope Spring MVC's ApplicationListener
[英]Errors with hibernate session in spring ApplicationListener
我無法猜測我的配置出了什么問題。 我需要在ApplicationListener中使用hibernate方法,但是不斷出現此錯誤:
Could not obtain transaction-synchronized Session for current thread
盡管在方法中使用了@Transactional。 這是ApplicationListener的實現:
@Component
public class FillIdOnStartup implements ApplicationListener<ContextRefreshedEvent>
{
@Inject
private MyRepository repository;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)
{
Iterable<Provider> products = repository.findAll();
}
}
這就是findAll()方法的樣子:
@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public Iterable<T> findAll()
{
return session().createQuery("from " + entityClass.getName()).getResultList();
}
怎么了? 謝謝
我找到了答案。 問題在於,諸如ApplicationListener,@ PostConstruct批注之類的東西在@Transactional之前被初始化。 這就是為什么休眠無法獲得當前會話的原因。 解決方案是直接在metod中打開會話並開始交易:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// some hibernate actions.
tx.commit();
session.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.