I can't guess what is wrong with my configuration. I need to use hibernate method within ApplicationListener, but constantly getting this error:
Could not obtain transaction-synchronized Session for current thread
despite the usage of @Transactional under method. This is ApplicationListener implementation:
@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:
@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. That is why hibernate can't get current session. The solution is to open session directly in metod and begin transaction:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// some hibernate actions.
tx.commit();
session.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.