Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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;
public class MyEJB {
* Container-managed transactional EntityManager.
EntityManager em;
SessionContext ctx;
* Allows to access current transaction details.
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.
* Method not invoked by the client, but by this EJB itself.
* It runs in
* separate transaction.
* @param callerTxKey
* method1() transaction key.
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) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.