Read data only through Spring + Hibernate

I noticed that if I want to read some data, and if I donโ€™t have a transaction context, I canโ€™t do it because

org.hibernate.HibernateException: session not found for current stream

A transaction is usually not required to read data.

So, in order for Spring to manage the session, it must have a transaction even for read operations like select ...?

Isn't that overhead?

PS.I do not want to open and close the session manually ...

Many thanks.

+6
source share
1 answer

@Transactional tells spring to open and close the session, and instruct it to start and complete the transaction. It is not very simple, but how it works. Therefore, if you do not have @Transactional , the session does not open. Here are your options:

  • use @Transactional(readOnly=true) - the goal is to have a read-only transaction. I recommend one
  • use JPA EntityManager using @PersistenceContext . It will open a new base session for each call. Not that good option. But you should consider using EntityManager with transaction readOnly = true
  • To open and close a session, use an additional aspect / interceptor / filter. This will be tricky, and you may end up getting confused about the implementation of the hibernate spring session concept.
+4
source

Source: https://habr.com/ru/post/910638/


All Articles