When using spring and hibernate, how are sessions/transactions handled? - java

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 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.

Related

Design Principal for JPA EntityManger

I am using JPA in a web application running in Tomcat 8. I am relatively new to JPA, and am having a hard time figuring out how to properly design my web app to use EntityManager. I have read "Java Persistence with Hibernate" and "Pro JPA 2", as well as a few posts about Entity Managers, but I am still unclear as to how to properly design my web app.
Should I create a singleton EntityManager that is used by the web app to service all requests, such as to CRUD (create, read, update, delete) entities?
Or should I ask the EntityManagerFactory to create a new EntityManager for each user request that comes in and close the EntityManager when I'm done processing the request?
I'm currently doing development on my local machine, where I am the only user.
What are the pros/cons of each approach?
Do both scale to hundreds of users?
I don't have the real world experience to answer these questions, so I'm looking for some answers/guidance from people who've used JPA in enterprise business apps.
Thanks
I have created ScopedEntityManager wrapper to ease JPA use in a servlet webapp. It creates an auto managed EM for the http request using a threadlocal variable.
It makes sure EM is rollbacked+closed after a servlet request. Same EM is returned in a getter method for the same request thread. You just need to commit() if all is good. Throwing an exception is not a problem because the request listener take care of the rollback().
See this how to instantiate a EM wrapper and life cycle manager.
https://github.com/Murmur/ScopedEntityManager/blob/master/src/es/claro/persistence/ScopedContextListener.java
https://github.com/Murmur/ScopedEntityManager
https://github.com/Murmur/ScopedEntityManager/blob/master/example_webapp/webapp/jpa1.jsp
So yes create a new EntityManager for each http request.

Transactions in Enterprise level application

I am trying to understand the transactions, and more specifically i am doing it using Spring framework. Going through the material that i have (both internet and books), i see these terminologies:
Container managed transactions (CMT).
Bean Managed transactions (BMT).
Java transaction API (JTA).
Also, for a large enterprise level application, terminologies like "local" and "global" transactions too i have encountered.
What i have understood, is that global transactions is for the cases in which we are managing two or more different resouces (like One Oracle DB, other MySQL etc) and commits/rollback to them happen if both are success/failure. Local transactions is for when we have only one resource to manage (like only one DB connection to MySQL).
I have following doubts:
While writing a simple JDBC standalone program, we can code to commit/rollback. I believe this is example of local transaction, is this correct? And is this transaction taken care by "JDBC" library itself or the drivers?
What is CMT? What i understand is that Container takes care of the transaction management (like Jboss AS). If this is correct, how internally does it manages? Are CMT local or global? Do they use JDBC API's internally to manage the transactions?
What is BMT? This i am not able to understand. We can have application deployed in an App server (and i believe in those cases the transaction would be managed by Container) or i can write an standalone application in which i can use the transaction management code myself (try .. catch block etc). So, which category BMT falls?
While reading Spring framework, i read that Spring framework have its own way of managing the transaction. Down the line, i read Spring Framework uses JTA to manage transactions? I am confused about this. If JTA is API, do we have multiple vendors who implement JTA (like for JPA, we can have multiple vendors who provide the implementation e.g. Hibernate).
Is JTA for local or global transactions? When i write a simple JDBC program to manage transaction, does it use API's which comply JTA? Or is JTA totally different from transaction management which simple JDBC program uses?
Same for CMT, does CMT follow the rules which JTA has in place (the API's primarily)?
It would be great if you answer point-wise, i did search on net, my doubts are still not answered.
Concerning local/global transaction: by global I suppose you are talking about XA transaction (2 phase commits : http://en.wikipedia.org/wiki/X/Open_XA). This is just mandatory when you deal with multiple databases or transactionnal resources.
yes it's a "local transaction", it means only one database is
part of the transaction. The transaction is managed by the database
and controlled by JDBC in that case.
CMT : Container Managed: the container will detect the start and
the end of the transaction and will perform commit/rollback
depending on method return status (successfull return : commit,
exception : rollback). CMT rely on JTA to manage transactions on its
resources. Then it's up to the proper resource adapters (RA) to talk
to jdbc or any other drivers related to your EIS (data). Look at
http://docs.oracle.com/javaee/5/tutorial/doc/bncjx.html
BMT: it means it's up to the bean to control transaction
boundaries. It's pretty rare to use this kind of transaction
management these days. With BMT you control the UserTransaction
object, it's an error to control transaction boundaries directly
with JDBC. Bear in mind also that even if you are in BMT some
framework like JPA (not JTA) will invalidate current transaction on
any error even if you did not explicitely requested a rollback. It
means it's quite hard/dangerous/useless to use BMT.
JTA (I hope you did not mispelled JPA) is at another level: JTA
the API a resource adapter must implement to be part of a container
transaction. Apart from UserTransaction class (what you'll use in
BMT to control transaction boundaries) you have nothing to do with
JTA. There is no multiple implementation of JTA but there is multiple implementation of JTS (Java Transaction Service), each application server vendor implements their own JTS.
JTA is a API for framework designer, JTA impose a contract to the
Resource Adapter RA, and the RA will use JDBC or any other API to
deal with it's EIS (Enterprise Information Storage, let's call it
your DB). JTA works for XA and non XA transactions (if your RA supports XA transactions).
CMT uses JTA, but again JTA is a lowlevel contract between
components of the application server. Application designer should
not care about JTA.

Transaction Management in EJB

Recently I was asked a question which left me thinking..want to get the community views on the same question.
I have a CustomerEJB which has say a createCustomer method. My EJB is exposed as a web service and hence createCustomer is one of its operations.
When a request hits createCustomer, 2 operations need to be performed
An INSERT SQL query into the database which may be adding certain data into db that came in input request
creation of a text file, say .txt in the file system.
Now the question is I want to couple these two tasks into a transaction. If any one task fails, I rollback the other task as well.
Without mentioning any hot technologies, like Spring/Hibernate what is the approach I can follow for Transaction management
My thoughts:
1. I can use JTA, demarcate the transaction boundaries and perform commit and rollback accordingly. JDBC can be used for the SQL task
2. I can use DAOs
Inviting your kind suggestions/comments
You would need to wrap the file creating in a XA capable JCA connector (not sure whether there's a ready made one out there, a quick good only found this fsconnector which doesn't support transactions yet), and use an XA driver for your DB transaction (most DBs will will be able handle this) and then wrap your EJB in an XA transaction (should be straightforward).
As long as both resources can handle the XA transactions, you'll get the benefit of 2-phase commits, which is what you're after.

How to wrap an object change in my own transaction and incorporate it with Hibernate to JTA?

I have a web-app, which I deploy on Tomcat 6 and it uses Hibernate.
It receives messages on a JMS queue which trigger changes both to my DB, via Hibernate and to an Object of mine (Agent).
The web-requests also access the DB, via Hibernate, and access the shared object (there's a ConcurrentHashMap<AgentId,Agent> held by a singleton).
My problem is that I have a JMS message which changes several different Agents and several tables and I need the changes in the Agents to be available if and only if the DB transaction completed successfully. In addition I do not want to employ read locks as that is too much of a performance hazard for me.
I was thinking of somehow implementing the XAResource interface for my singleton and then use JTA to manage both my singleton and my Hibernate transaction.
What do you think? Does it sound reasonable? Am I way off?
If any additional details are needed please don't hesitate to ask
Ittai
Instead of implementing XAResource, you could use a transactional cache like EHCache which supports JTA since 2.0 (i.e. it can act as an XA resource and participate in a XA transaction alongside other XA resources).

Hibernate Session scope in JTA transactions vs Open-Session-In-View

Is it correct to say that using JTA Transactions with Hibernate contrasts using the Open-Session-In-View with regards to the session scope?
From what I've been able to gather the Session scope in the JTA Transactions is a transaction (mainly based on this link) while in the Open-Session-In-View pattern the session's scope is the requrest and you can have multiple transactions in it.
I'm asking, first to understand, and secondly to verify "Who" is responsible for the session handling when using JTA.
Currently, when using the Open-Session-In-View, I have a HibernateUtil class which handles opening, retrieving and closing of sessions (via ThreadLocal<Session>).
When I'll switch over to using JTA will Hibernate handle the above session actions? (as a derivative maybe of my calling userTransaction.begin,userTransaction.rollback)
BTW, I'm asking about JTA as I need to coordinate a transaction across Hibernate JMS and EHCache so this isn't a general best-practices "lets-use-JTA" question.
Ittai
Well, if you're using JTA then the JTA manager (usually EJB3 container) is responsible for transactions.
Typically, the same good old open-transaction-in-view model is used, however with UserTransaction and, say, a SWING client it's possible to have long-lasting transactions spanning multiple requests (though it's a bad practice in general).
BTW, I'm asking about JTA as I need to coordinate a transaction across Hibernate JMS and EHCache so this isn't a general best-practices "lets-use-JTA" question.
Good luck. I found that external transaction manager (I've used Atomikos) + Spring worked better for my needs than JBoss.

Categories