Java EE 7中的非同步持久性上下文
JPA 2.1引入了非同步持久性上下文的概念,该概念允许对JPA实体管理器的刷新进行细粒度控制,即通过显式调用EntityManager#joinTransaction 。 以前,这默认情况下是JTA事务的结束,例如,在典型的Stateless EJB中,实体管理器会在方法结束时(默认情况下开始和结束事务)将其状态刷新到DB。 您可以在这里和这里阅读有关此内容的更多信息。
在Java EE 7之前的时代(EE 5和EE 6)也有可能
可以对Java EE 5和6进行调整,以实现与Java EE 7中的非同步持久性上下文所获得的结果相同的结果。
想象一个用例,其中按顺序(使用流程之类的向导)来编辑客户详细信息,例如屏幕1中的地址信息,屏幕2中的联系信息等。您希望在客户输入是,但不希望将整个状态推送到数据库,直到该过程完成,即用户输入了所有类别的信息
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