Archive for November, 2007

Conversations with JPA Naturally, an interceptor that wraps (Cheapest web hosting)

Tuesday, November 20th, 2007

Conversations with JPA Naturally, an interceptor that wraps the getAuction() and endAuction() methods and supplies the correct EntityManager instance can be more convenient. It also avoids the concern leaking upward to the presentation layer. You d get this interceptor for free if you wrote your controller as a stateful EJB session bean. When you try to apply this strategy with an extended persistence context that spans the whole conversation, you ll probably run into an issue that can break atomicity of the conversation automatic flushing. Preventing automatic flushing Consider the following conversation, which adds an event as an intermediate step: // Begin persistence context and conversation EntityManager em = emf.createEntityManager(); ManageAuctionExtended controller = new ManageAuctionExtended(em); // First event Item item = controller.getAuction( 1234l ); // Item is displayed on screen and modified… item.setDescription(”[SOLD] An item for sale”); // Second event if ( !controller.sellerHasEnoughMoney(seller) ) throw new RuntimeException(”Seller can’t afford it!”); // Third event controller.endAuction(item); // End persistence context and conversation em.close(); From looking at this new conversation client code, when do you think the updated item description is saved in the database? It depends on the flushing of the persistence context. You know that the default FlushMode in JPA is AUTO, which enables synchronization before a query is executed, and when a transaction is committed. The atomicity of the conversation depends on the implementation of the sellerHasEnoughMoney() method and whether it executes a query or commits a transaction. Let s assume you wrap the operations that execute inside that method with a regular transaction block: public class ManageAuctionExtended { … public boolean sellerHasEnoughMoney(User seller) { EntityTransaction tx = em.getTransaction(); tx.begin();
We recommend high quality webhost to host and run your jsp application: christian web host services.

CHAPTER 11 Implementing conversations public static class ManageAuctionExtended (Starting a web site)

Monday, November 19th, 2007

CHAPTER 11 Implementing conversations public static class ManageAuctionExtended { EntityManager em; public ManageAuctionExtended(EntityManager em) { this.em = em; } public Item getAuction(Long itemId) { EntityTransaction tx = em.getTransaction(); tx.begin(); Item item = em.find(Item.class, itemId); tx.commit(); return item; } public Item endAuction(Item item) { EntityTransaction tx = em.getTransaction(); tx.begin(); // Merge item Item mergedItem = em.merge(item); // Set winning bid // Charge seller // Notify seller and winner // … this code uses mergedItem! tx.commit(); return mergedItem; } } The controller expects that the persistence context for the whole conversation is set in its constructor. The client now creates and closes the EntityManager: // Begin persistence context and conversation EntityManager em = emf.createEntityManager(); ManageAuctionExtended controller = new ManageAuctionExtended(em); // First event Item item = controller.getAuction( 1234l ); // Item is displayed on screen and modified… item.setDescription(”[SOLD] An item for sale”); // Second event controller.endAuction(item); // End persistence context and conversation em.close();
We recommend high quality webhost to host and run your jsp application: christian web host services.

Most popular web site - Conversations with JPA returned Item, mergedItem, is a

Sunday, November 18th, 2007

Conversations with JPA returned Item, mergedItem, is a different instance! The client now has two Item objects: the old one and the new one. As we pointed out in Merging the state of a detached object in section 9.3.2, the reference to the old instance should be considered obsolete by the client: It doesn t represent the latest state. Only the mergedItem is a reference to the up-todate state. With merging instead of reattachment, it becomes the client s responsibility to discard obsolete references to stale objects. This usually isn t an issue, if you consider the following client code: ManageAuction controller = new ManageAuction(); // First event Item item = controller.getAuction( 1234l ); // Item is displayed on screen and modified… item.setDescription(”[SOLD] An item for sale”); // Second event item = controller.endAuction(item); The last line of code sets the merged result as the itemvariable value, so you effectively update this variable with a new reference. Keep in mind that this line updates only this variable. Any other code in the presentation layer that still has a reference to the old instance must also refresh variables be careful. This effectively means that your presentation code has to be aware of the differences between reattachment and merge strategies. We ve observed that applications that have been constructed with an extended persistence context strategy are often easier to understand than applications that rely heavily on detached objects. 11.3.3 Extending the persistence context in Java SE We already discussed the scope of a persistence context with JPA in Java SE in chapter 10, section 10.1.3, Transactions with Java Persistence. Now we elaborate on these basics and focus on examples that show an extended persistence context with a conversation implementation. The default persistence context scope In JPA without EJBs, the persistence context is bound to the lifecycle and scope of an EntityManager instance. To reuse the same persistence context for all events in a conversation, you only have to reuse the same EntityManager to process all events. An unsophisticated approach delegates this responsibility to the client of the conversation controller:
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

CHAPTER 11 Implementing conversations second event, the (probably

Saturday, November 17th, 2007

CHAPTER 11 Implementing conversations second event, the (probably modified) item is reattached to a new persistence context and the auction is closed. Listing 11.6 shows the same controller, which can serve both events, with JPA and merging: Listing 11.6 A controller that uses JPA to merge a detached object public class ManageAuction { public Item getAuction(Long itemId) { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Item item = em.find(Item.class, itemId); tx.commit(); em.close(); return item; } public Item endAuction(Item item) { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); // Merge item Item mergedItem = em.merge(item); // Set winning bid // Charge seller // Notify seller and winner // … this code uses mergedItem! tx.commit(); em.close(); return mergedItem; } } There should be no code here that surprises you you ve seen all these operations many times. Consider the client that calls this controller, which is usually some kind of presentation code. First, the getAuction() method is called to retrieve an Item instance for display. Some time later, the second event is triggered, and the endAuction() method is called. The detached Item instance is passed into this method; however, the method also returns an Item instance. The
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

Conversations with JPA You (Make a web site) can instantiate an

Friday, November 16th, 2007

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.

CHAPTER 11 Implementing conversations 11.3.1 Persistence context propagation (Web and email hosting)

Thursday, November 15th, 2007

CHAPTER 11 Implementing conversations 11.3.1 Persistence context propagation in Java SE Consider again the controller from listing 11.1. This code relies on DAOs that execute the persistence operations. Here is again the implementation of such a data access object with Hibernate APIs: public class ItemDAO { public Bid getMaxBid(Long itemId) { Session s = getSessionFactory().getCurrentSession(); return (Bid) s.createQuery(”…”).uniqueResult(); } … } If you try to refactor this with JPA, your only choice seems to be this: public class ItemDAO { public Bid getMaxBid(Long itemId) { Bid maxBid; EntityManager em = null; EntityTransaction tx = null; try { em = getEntityManagerFactory().createEntityManager(); tx = em.getTransaction(); tx.begin(); maxBid = (Bid) em.createQuery(”…”) .getSingleResult(); tx.commit(); } finally { em.close(); } return maxBid; } … } No persistence-context propagation is defined in JPA, if the application handles the EntityManager on its own in Java SE. There is no equivalent to the getCurrentSession() method on the Hibernate SessionFactory. The only way to get an EntityManager in Java SE is through instantiation with the createEntityManager() method on the factory. In other words, all your data access methods use their own EntityManager instance this is the session-peroperation antipattern we identified earlier! Worse, there is no sensible location for transaction demarcation that spans several data access operations. There are three possible solutions for this issue:
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Conversations with (Shared web hosting) JPA 11.3 Conversations with JPA We

Wednesday, November 14th, 2007

Conversations with JPA 11.3 Conversations with JPA We now look at persistence context propagation and conversation implementation with JPA and EJB 3.0. Just as with native Hibernate, you must consider three points when you want to implement conversations with Java Persistence: You want to propagate the persistence context so that one persistence context is used for all data access in a particular request. In Hibernate, this functionality is built in with the getCurrentSession() feature. JPA doesn t have this feature if it s deployed stand-alone in Java SE. On the other hand, thanks to the EJB 3.0 programming model and the well-defined scope and lifecycle of transactions and managed components, JPA in combination with EJBs is much more powerful than native Hibernate. If you decide to use a detached objects approach as your conversation implementation strategy, you need to make changes to detached objects persistent. Hibernate offers reattachment and merging; JPA only supports merging. We discussed the differences in the previous chapter in detail, but we want to revisit it briefly with more realistic conversation examples. If you decide to use the session-per-conversation approach as your conversation implementation strategy, you need to extend the persistence context to span a whole conversation. We look at the JPA persistence context scopes and explore how you can implement extended persistence contexts with JPA in Java SE and with EJB components. Note that we again have to deal with JPA in two different environments: in plain Java SE and with EJBs in a Java EE environment. You may be more interested in one or the other when you read this section. We previously approached the subject of conversations with Hibernate by first talking about context propagation and then discussing long conversations. With JPA and EJB 3.0, we ll explore both at the same time, but in separate sections for Java SE and Java EE. We first implement conversations with JPA in a Java SE application without any managed components or container. We re often going to refer to the differences between native Hibernate conversations, so make sure you understood the previous sections of this chapter. Let s discuss the three issues we identified earlier: persistence context propagation, merging of detached instances, and extended persistence contexts.
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

CHAPTER 11 Implementing conversations (Bulletproof web design) The invoke(Method) interceptor wraps

Tuesday, November 13th, 2007

CHAPTER 11 Implementing conversations The invoke(Method) interceptor wraps around the execute() operation of the controller. This interception code runs every time a request from the application user has to be processed. When it returns, you check whether the return value contains a special token or marker. This token signals that this was the last event that has to be processed in a particular conversation. You now flush the Session, commit all changes, and close the Session. If this wasn t the last event of the conversation, you commit the database transaction, store the disconnected Session, and continue to wait for the next event in the conversation. This interceptor is transparent for any client code that calls execute(). It s also transparent to any code that runs inside execute (): Any data access operation uses the current Session; concerns are separated properly. We don t even have to show you the data-access code, because it s free from any database transaction demarcation or Session handling. Just load and store objects with getCurrentSession(). The following questions are probably on your mind: Where is the disconnectedSession stored while the application waits for the user to send the next request in a conversation? It can be stored in the HttpSession or even in a stateful EJB. If you don t use EJBs, this responsibility is delegated to your application code. If you use EJB 3.0 and JPA, you can bind the scope of the persistence context, the equivalent of a Session, to a stateful EJB another advantage of the simplified programming model. Where does the special token that marks the end of the conversation come from? In our abstract example, this token is present in the return value of the execute() method. There are many ways to implement such a special signal to the interceptor, as long as you find a way to transport it there. Putting it in the result of the event processing is a pragmatic solution. This completes our discussion of persistence-context propagation and conversation implementation with Hibernate. We shortened and simplified quite a few examples in the past sections to make it easier for you to understand the concepts. If you want to go ahead and implement more sophisticated units of work with Hibernate, we suggest that you first also read chapter 16. On the other hand, if you aren t using Hibernate APIs but want to work with Java Persistence and EJB 3.0 components, read on.
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Conversations with Hibernate This (Web hosting isp) sounds more complex than

Monday, November 12th, 2007

Conversations with Hibernate This sounds more complex than it is in code. Listing 11.5 is a pseudoimplementation of such an interceptor: Listing 11.5 An interceptor implements the session-per-conversation strategy public class ConversationInterceptor { public Object invoke(Method method) { // Which Session to use? Session currentSession = null; if (disconnectedSession == null) { // Start of a new conversation currentSession = sessionFactory.openSession(); currentSession.setFlushMode(FlushMode.MANUAL); } else { // In the middle of a conversation currentSession = disconnectedSession; } // Bind before processing event ManagedSessionContext.bind(currentSession); // Begin a database transaction, reconnects Session currentSession.beginTransaction(); // Process the event by invoking the wrapped execute() Object returnValue = method.invoke(); // Unbind after processing the event currentSession = ManagedSessionContext.unbind(sessionFactory); // Decide if this was the last event in the conversation if ( returnValue.containsEndOfConversationToken() ) { // The event was the last event: flush, commit, close currentSession.flush(); currentSession.getTransaction().commit(); currentSession.close(); disconnectedSession = null; // Clean up } else { // Event was not the last event, continue conversation currentSession.getTransaction().commit(); // Disconnects disconnectedSession = currentSession; } return returnValue; } }
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Domain and web hosting - CHAPTER 11 Implementing conversations s.beginTransaction() s = sf.openSession()

Sunday, November 11th, 2007

CHAPTER 11 Implementing conversations s.beginTransaction() s = sf.openSession() s.setFlushMode(MANUAL) MSC.bind(s) commit() s = MSC.unbind() 1. 2. 3. 4. s.beginTransaction() commit() 6. 8. MSC.bind(s) 5. 7. s = MSC.unbind() 9. s.close() s.flush() Figure 11.4 Interception of events to manage the lifecycle of a Session called before and after this method executes. This is shown in figure 11.4; read the numbered items from left to right. When the first request in a conversation hits the server, the interceptor runs and opens a new Session B; automatic flushing of this Session is immediately disabled. This Session is then bound into Hibernate s ManagedSessionContext. A transaction is started Cbefore the interceptor lets the controller handle the event. All code that runs inside this controller (or any DAO called by the controller) can now call sessionFactory.getCurrentSession() and work with the Session. When the controller finishes its work, the interceptor runs again and unbinds the current Session D. After the transaction is committed E, the Session is disconnected automatically and can be stored during user think-time. Now the server waits for the second request in the conversation. As soon as the second request hits the server, the interceptor runs, detects that there is a disconnected stored Session, and binds it into the ManagedSession- Context F. The controller handles the event after a transaction was started by the interceptor G. When the controller finishes its work, the interceptor runs again and unbinds the current Session from Hibernate. However, instead of disconnecting and storing it, the interceptor now detects that this is the end of the conversation and that the Session needs to be flushed H, before the transaction is committed I. Finally, the conversation is complete and the interceptor closes the Session J.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.