6

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.

1 Answer 1

4

@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.
3
  • I use Spring + Hibernate (without JPA).Now for reading some data and in order for Spring to manage the session I need to use @@Transactional.I have the option for me to open and close the session manually, but i think is not elegant ?!.But I have this thing in mind that usign @@Transactional even with read only .it is the same as not using read only and there is some potential overhead..
    – Cris
    Mar 13, 2012 at 21:43
  • readonly is effective only when you want to prevent writing data as far as i know..ibm.com/developerworks/java/library/j-ts1/index.html
    – Cris
    Mar 13, 2012 at 21:45
  • 1
    don't worry about the overhead, even if there's any.
    – Bozho
    Mar 13, 2012 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.