when using hibernate with spring, can someone explain how the session unit of work and transactions are handled?
- is the transaction started at the beginning of the page request, and committed at the end?
- can I have multiple db calls per request, that each have different transaction开发者_StackOverflow中文版 levels? e.g. some are left as default, while others are read-uncommitted?
is the transaction started at the beginning of the page request, and committed at the end?
In a web application, opening / closing the Session
is usually done using the "Open Session in View" pattern. Spring comes with a OpenSessionInViewFilter
or an OpenSessionInViewInterceptor
for this. Both make Hibernate Sessions
available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via HibernateTransactionManager
or JtaTransactionManager
as well as for non-transactional execution (if configured appropriately).
Transaction demarcation is usually done at the service methods level, using Spring AOP to wrap them inside transactions.
can I have multiple db calls per request, that each have different transaction levels? e.g. some are left as default, while others are read-uncommitted?
You can have nested transactions with different isolation levels. Refer to the Transaction Management chapter.
It's usually configured declaratively with aspect oriented programming (AOP). You can define what beans, classes, packages or methods require transactions and Spring will provide it in a fashion similar to EJBs. Thanks to AOP you have full control over what exactly and how is wrapped into transactions.
Read more about it here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative
to your questions:
1-is the transaction started at the beginning of the page request, and committed at the end?
Not exactly. the usual workflow of spring MVC is:
requestDispatcher->Controller->Service call(transaction starts and ends here)
Services may invoke Daos, Daos will talk to Datastore via Hibernate.
A transaction can continue living after the http response. e.g. service run in a thread.
2-can I have multiple db calls per request, that each have different transaction levels? e.g. some are left as default, while others are read-uncommitted?
Yes certainly you can. let's say, your application does a migration job. a request says "start migration!" Then your service will read data via source database, and do some magic base on your migration logic, finally write to target database, and commit the transaction.
精彩评论