I have a 3 layer application using spring and hibernate (controller -> service -> dao) and transaction is applied to service layer. I don't configure OpenSessionInViewInterceptor or OpenSessionInViewFilter and I want to know the hibernate session control behavior. Open session per transaction or per request? Thanks!
Spring opens a new Hibernate Session at the beginning of the request. These Sessions are not necessarily connected to the database. Every time the application needs a Session, it will reuse the already existing one. At the end of the request, the same interceptor closes that Session.
Most importantly, the SessionFactory in Hibernate is responsible for the creation of Session objects. The Hibernate Session provides methods such as save, delete and update, all of which are used to perform CRUD-based operations on the database to which the SessionFactory connects.
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
Generally the @Transactional annotation is written at the service level. It is used to combine more than one writes on a database as a single atomic operation. When somebody call the method annotated with @Transactional all or none of the writes on the database is executed.
If you're using the HibernateTransactionManager
, a Session
will get bound to the current thread and flushed and closed when the transaction ends, either through commit or roll back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With