Skip to main content

Entity manager in web applications

1 reply [Last post]
Joined: 2006-09-01

I'm confused about using an entity manager in a web application. I would like to use container managed persitence. Now my questions:

1) can I inject an entity manager factory in a multithreaded servlet?

2) can I use only one and the same entity manager in the context of one transaction or is it possible to use different entity managers within one transaction by injecting the entity manager factory in the different objects?

Thanks in advanced

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-03-30

There is nothing called [i]container managed persistence[/i] in Java Persistence API. Are you referring to [i]container managed entity manager[/i]?

If you are using a Servlet 2.5 compliant container like GlassFish (note Tomcat 5.x is not Servlet 2.5 compliant), then I suggest you use [b]container managed entity manager[/b]. This can be obtained either by [b]injection[/b] (@PersistenceContext) or [b]JNDI[/b] lookup. Since you must [b]not[/b] inject an entity manager into a multi-threaded servlet, you are left with the option of looking up an entity manager using JNDI in the doGet() or doPost() method of the servlet. This is further explained at

You may then ask, how can one use @PersistenceContext in web application, the answer is, it can be used in [b]request scoped JSF managed beans[/b].