简体   繁体   English

Spring ApplicationListener中的休眠会话错误

[英]Errors with hibernate session in spring ApplicationListener

I can't guess what is wrong with my configuration. 我无法猜测我的配置出了什么问题。 I need to use hibernate method within ApplicationListener, but constantly getting this error: 我需要在ApplicationListener中使用hibernate方法,但是不断出现此错误:

Could not obtain transaction-synchronized Session for current thread

despite the usage of @Transactional under method. 尽管在方法中使用了@Transactional。 This is ApplicationListener implementation: 这是ApplicationListener的实现:

@Component
public class FillIdOnStartup implements ApplicationListener<ContextRefreshedEvent>
{
    @Inject
    private MyRepository repository;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)
    {
        Iterable<Provider> products = repository.findAll();
    }
}

This is how findAll() method looks like: 这就是findAll()方法的样子:

@Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public Iterable<T> findAll()
    {
        return session().createQuery("from " + entityClass.getName()).getResultList();
    }

What is wrong? 怎么了? Thank you 谢谢

I found the answer. 我找到了答案。 The problem is that such things like ApplicationListener, @PostConstruct annotations are initialized BEFORE @Transactional. 问题在于,诸如ApplicationListener,@ PostConstruct批注之类的东西在@Transactional之前被初始化。 That is why hibernate can't get current session. 这就是为什么休眠无法获得当前会话的原因。 The solution is to open session directly in metod and begin transaction: 解决方案是直接在metod中打开会话并开始交易:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// some hibernate actions.
tx.commit();
session.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM