File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Spring-Injected EntityManagers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Spring-Injected EntityManagers" Watch "Spring-Injected EntityManagers" New topic

Spring-Injected EntityManagers

John Eric Hamacher
Ranch Hand

Joined: Apr 25, 2007
Posts: 230

In the Spring documentation (section 13.5.2) I see a DAO:

which is described as a thread-safe way to use a shared EntityManager. So I assume this means I could use this DAO as a singleton in a web container and not have to worry about different users grabbing the same EntityManager?
Just want to make sure. Just learning this stuff.

Thanks, Eric
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
Hi Eric,
Basically, spring by default nature is handing over singleton objects. Now what you are seeing is the instance of entity manager will be
provided via entity manager factory which you have already configured in the context. As these resources are pretty expensive, the responsibility
is of entity manager factory to give the manager when desired. Resource intensive things like entity manager factory implement singleton pattern
themselves, so always a singleton object will be handed over. Thread safety is a different thing, i guess some of the responsibility, programmer has
to cater themsevles also. I will strongly welcome some other opinions as well. Eric, there should be one entity manager for a whole complete web application,
so yes you should not worry about shared entity manager at all.

My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
John Eric Hamacher
Ranch Hand

Joined: Apr 25, 2007
Posts: 230
Thanks for the response. I can use this code for multiple transactions (all using the same DAO) on a single thread and somehow it knows to create a new EntityManager for each. The documentation seems very nonchalant about this but it is usually very good to warn about misuse of what it presents. I wonder if AOP is helping but I never specified any AOP in my application context.

Thanks, Eric
I agree. Here's the link:
subject: Spring-Injected EntityManagers
It's not a secret anymore!