0

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

Sviatlana
  • 1,728
  • 6
  • 27
  • 55

1 Answers1

0

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();
Sviatlana
  • 1,728
  • 6
  • 27
  • 55