Conversations with JPA You (Make a web site) can instantiate an
Conversations with JPA You can instantiate an EntityManager for the whole DAO when the DAO is created. This doesn t get you the persistence-context-per-request scope, but it s slightly better than one persistence context per operation. However, transaction demarcation is still an issue with this strategy; all DAO operations on all DAOs still can t be grouped as one atomic and isolated unit of work. You can instantiate a single EntityManager in your controller and pass it into all DAOs when you create the DAOs (constructor injection). This solves the problem. The code that handles an EntityManager can be paired with transaction demarcation code in a single location, the controller. You can instantiate a single EntityManager in an interceptor and bind it to a ThreadLocal variable in a helper class. The DAOs retrieve the current EntityManager from the ThreadLocal. This strategy simulates the getCurrentSession() functionality in Hibernate. The interceptor can also include transaction demarcation, and you can wrap the interceptor around your controller methods. Instead of writing this infrastructure yourself, consider EJBs first. We leave it to you which strategy you prefer for persistence-context propagation in Java SE. Our recommendation is to consider Java EE components, EJBs, and the powerful context propagation that is then available to you. You can easily deploy a lightweight EJB container with your application, as you did in chapter 2, section 2.2.3, Introducing EJB components. Let s move on to the second item on the list: the modification of detached instances in long conversations. 11.3.2 Merging detached objects in conversations We already elaborated on the detached object concept and how you can reattach modified instances to a new persistence context or, alternatively, merge them into the new persistence context. Because JPA offers persistence operations only for merging, review the examples and notes about merging with native Hibernate code (in Merging the state of a detached object in chapter 9, section 9.3.2.) and the discussion of detached objects in JPA, chapter 9, section 9.4.2, Working with detached entity instances. Here we want to focus on a question we brought up earlier and look at it from a slightly different perspective. The question is, Why is a persistent instance returned from the merge() operation? The long conversation you previously implemented with Hibernate has two steps, two events. In the first event, an auction item is retrieved for display. In the
In case you need quality webspace to host and run your web applications, try our personal web hosting services.