Java Reference
In-Depth Information
testing, once the application comes under increased load it may behave unpredictably. It's
best to use EntityManager s from within EJBs. If you must access the EntityMan-
ager directly, you can use the following code snippet or access the EntityManager-
Factory :
@PersistenceContext(name="pu/actionBazaar" unitName="ActionBazaar")
public class ItemServlet extends HttpServlet {
private UserTransaction ut;
public void service(HttpSerlvetRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Context ctx = new InitialContext();
EntityManager em = (EntityManager)ctx.lookup("java:comp/env/pu/
The other alternative is to use an application-managed EntityManager with a JTA
transaction. It's worth noting that EntityManagerFactory is thread-safe.
10.1.6. Injecting the EntityManagerFactory
In the previous section you saw how the container injects the EntityManager . When
the container injects the EntityManager , you have very little control over the
EntityManager 's lifecycle. In some situations you want fine-grained control over the
lifecycle of the EntityManager as well as transaction management. For this reason,
as well as to maintain flexibility, JPA provides injection support for the EntityMan-
agerFactory . Using the EntityManagerFactory , you can get EntityManager
instances that you can fully control. An example of the ItemManager controlling its
EntityManager instance manually is shown in the following listing.
Search WWH ::

Custom Search