Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read only data via Spring + Hibernate

Noticed that if I want to read some data and if I do not have a transaction context I will not be able to do so because

org.hibernate.HibernateException: No Session found for current thread

For reading data , is not required a transaction normally.

So in order for Spring to manage the session it needs to have a transaction even for read only operations like selects... ?

Is that not an overhead ?

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

Thanks a lot.

like image 680
Cris Avatar asked Mar 13 '12 21:03

Cris


1 Answers

@Transactional tells spring to open and close a session, in addition to instructing it to start and commit a transaction. This is not very straightforward, but that's how it works. So if you don't have @Transactional, no session gets opened. Here are your options:

  • use @Transactional(readOnly=true) - the purpose is to have a read-only transaction. I recommend that one
  • use JPA EntityManager injected with @PersistenceContext. It will open a new underlying session for each invocation. Not that good option. But you should consider using EntityManager with a readOnly=true transaction
  • Use an additional aspect/interceptor/filter to open and close session. That would be hard, and you may end up confused by the spring implementation of hibernate's current session concept.
like image 87
Bozho Avatar answered Nov 04 '22 01:11

Bozho