Skip to content

Instantly share code, notes, and snippets.

@PiotrNowicki
Created November 23, 2011 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PiotrNowicki/1388726 to your computer and use it in GitHub Desktop.
Save PiotrNowicki/1388726 to your computer and use it in GitHub Desktop.
Am I in the same transaction? Am I using the same PersistenceContext?
package com.piotrnowicki;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.TransactionSynchronizationRegistry;
import org.eclipse.persistence.jpa.JpaEntityManager;
@Stateless
public class MyEJB {
/**
* Container-managed transactional EntityManager.
*/
@PersistenceContext
EntityManager em;
@Resource
SessionContext ctx;
/**
* Allows to access current transaction details.
*/
@Resource
TransactionSynchronizationRegistry tsr;
/**
* Method invoked by the client.
* Default transaction attribute = REQUIRED.
*/
public void myMethod1() {
// Using EclipseLink, so use this provider's specific class to
// get to the EntityManager.
JpaEntityManager delegate = em.unwrap(JpaEntityManager.class);
Object txKey = tsr.getTransactionKey();
print("[method1] Server proxy for EntityManager EM: " + em);
print("[method1] EclipseLink EntityManager: " + delegate);
print("[method1] Tx key: " + txKey);
// If uncommented - a local, non-ejb, call would be made.
// myMethod2(txKey);
// Necessary if you want to invoke ejb-aware call.
ctx.getBusinessObject(MyEJB.class).myMethod2(txKey);
}
/**
* Method not invoked by the client, but by this EJB itself.
* It runs in
* separate transaction.
*
* @param callerTxKey
* method1() transaction key.
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void myMethod2(Object callerTxKey) {
JpaEntityManager delegate = em.unwrap(JpaEntityManager.class);
Object txKey = tsr.getTransactionKey();
// The TransactionKey implementation must override hashCode()
// and equals(), so we can use equals() to compare transactions.
boolean sameTx = txKey.equals(callerTxKey);
print("[method2] Server proxy for EntityManager EM: " + em);
print("[method2] EclipseLink EntityManager: " + delegate);
print("[method2] Tx key: " + txKey);
print("[method2] Is Tx1 the same as Tx2? " + sameTx);
}
/**
* Just a minor helper method to print message on the console.
*
* @param msg
* message to be printed.
*/
private void print(String msg) {
System.out.println(msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment