Last active
December 4, 2015 04:37
-
-
Save abhirockzz/ea543c4eadb7d0ee5cf1 to your computer and use it in GitHub Desktop.
Leveraging Stateful EJBs with extended Persistence Context and flexible transaction demarcations to achieve results similar to an Unsynchronized Persistent Context (JPA 2.1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 5 | |
Principal authenticatedUser; | |
private Customer customer; | |
@PostConstruct | |
public void init(){ | |
System.out.println("CustomerEditorFacade created at " + new Date().toString()); | |
} | |
@PreDestroy | |
public void destroy(){ | |
System.out.println("CustomerEditorFacade destroyed at " + new Date().toString()); | |
} | |
//step 1 | |
public 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 Database | |
Customer customerFromDB = em.find(Customer.class, Integer.valueOf(custID)); //obtain a 'managed' entity | |
customerFromDB.setCity(city); //no need to call em.persist | |
customer = customerFromDB; //just switch references | |
//Customer state will NOT be pushed to DB | |
} | |
//step 2 | |
public 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 | |
} | |
@Remove | |
public void finish(){ | |
//optional method to provide a way to evict this bean once used | |
//not required if this is session scoped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment