Java EE 7之前版本替代JPA 2.1的非同步持久性上下文
Java EE 7中的非同步持久性上下文
JPA 2.1引入了非同步持久性上下文的概念,該概念允許對(duì)JPA實(shí)體管理器的刷新進(jìn)行細(xì)粒度控制,即通過顯式調(diào)用EntityManager#joinTransaction 。 以前,這默認(rèn)情況下是JTA事務(wù)的結(jié)束,例如,在典型的Stateless EJB中,實(shí)體管理器會(huì)在方法結(jié)束時(shí)(默認(rèn)情況下開始和結(jié)束事務(wù))將其狀態(tài)刷新到DB。 您可以在這里和這里閱讀有關(guān)此內(nèi)容的更多信息。
在Java EE 7之前的時(shí)代(EE 5和EE 6)也有可能
可以對(duì)Java EE 5和6進(jìn)行調(diào)整,以實(shí)現(xiàn)與Java EE 7中的非同步持久性上下文所獲得的結(jié)果相同的結(jié)果。
想象一個(gè)用例,其中按順序(使用流程之類的向?qū)?#xff09;來編輯客戶詳細(xì)信息,例如屏幕1中的地址信息,屏幕2中的聯(lián)系信息等。您希望在客戶輸入是,但不希望將整個(gè)狀態(tài)推送到數(shù)據(jù)庫,直到該過程完成,即用戶輸入了所有類別的信息
package com.abhirockzz.conversationalee;import com.abhirockzz.conversationalee.entity.Customer; import java.util.Date; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Remove; import javax.ejb.Stateful; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType;@Stateful @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class CustomerEditorFacade{@PersistenceContext(type = PersistenceContextType.EXTENDED)EntityManager em;@Inject //this won't work in Java EE 5Principal authenticatedUser;private Customer customer;@PostConstructpublic void init(){System.out.println("CustomerEditorFacade created at " + new Date().toString()); }@PreDestroypublic void destroy(){System.out.println("CustomerEditorFacade destroyed at " + new Date().toString()); }//step 1public void updateCity(String custID, String city){String custID = authenticatedUser.getName(); //assume we have an authenticated principal which is the same as the customer ID in the DatabaseCustomer customerFromDB = em.find(Customer.class, Integer.valueOf(custID)); //obtain a 'managed' entitycustomerFromDB.setCity(city); //no need to call em.persistcustomer = customerFromDB; //just switch references//Customer state will NOT be pushed to DB}//step 2public void updateEmail(String email){customer.setEmail(email); //not pushed to DB yet}@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)public void save(){//dummy method to trigger transaction and flush EM state to DB}@Removepublic void finish(){//optional method to provide a way to evict this bean once used//not required if this is session scoped}}代碼注釋是自我解釋(希望如此)
干杯!
翻譯自: https://www.javacodegeeks.com/2015/12/pre-java-ee-7-alternative-jpa-2-1-unsynchronized-persistence-context.html
總結(jié)
以上是生活随笔為你收集整理的Java EE 7之前版本替代JPA 2.1的非同步持久性上下文的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 希腊罗马神话和《圣经》中的英语典故
- 下一篇: 百度集团资深副总裁李震宇:Apollo开