1 19 package org.apache.cayenne.jpa; 20 21 import javax.persistence.EntityTransaction; 22 import javax.persistence.TransactionRequiredException; 23 import javax.transaction.Status ; 24 import javax.transaction.Synchronization ; 25 import javax.transaction.TransactionSynchronizationRegistry ; 26 27 import org.apache.cayenne.ObjectContext; 28 29 34 public class JtaEntityManager extends ResourceLocalEntityManager { 35 36 protected Object currentTxKey; 37 38 public JtaEntityManager(ObjectContext context, JtaEntityManagerFactory factory) { 39 super(context, factory); 40 } 41 42 private JtaEntityManagerFactory getJtaFactory() { 43 return (JtaEntityManagerFactory) getFactory(); 44 } 45 46 49 public EntityTransaction getTransaction() { 50 throw new IllegalStateException ( 51 "'getTransaction' is called on a JTA EntityManager"); 52 } 53 54 61 @Override 62 public void joinTransaction() { 63 if (currentTxKey == null) { 64 TransactionSynchronizationRegistry registry = getJtaFactory() 65 .getTransactionRegistry(); 66 registry.registerInterposedSynchronization(new TransactionBinding()); 67 currentTxKey = registry.getTransactionKey(); 68 } 69 } 70 71 74 @Override 75 public void persist(Object entity) { 76 checkTransaction(); 77 super.persist(entity); 78 } 79 80 83 @Override 84 public <T> T merge(T entity) { 85 checkTransaction(); 86 return super.merge(entity); 87 } 88 89 92 @Override 93 public void remove(Object entity) { 94 checkTransaction(); 95 super.remove(entity); 96 } 97 98 101 @Override 102 public void refresh(Object entity) { 103 checkTransaction(); 104 super.refresh(entity); 105 } 106 107 110 public void flush() { 111 checkTransaction(); 112 super.flush(); 113 }; 114 115 118 protected void checkTransaction() throws TransactionRequiredException { 119 if (!getJtaFactory().isActiveTransaction()) { 120 throw new TransactionRequiredException(); 121 } 122 } 123 124 class TransactionBinding implements Synchronization { 125 126 public void afterCompletion(int status) { 127 if (status != Status.STATUS_COMMITTED) { 128 clear(); 129 } 130 131 currentTxKey = null; 132 } 133 134 public void beforeCompletion() { 135 flush(); 136 } 137 } 138 } 139 | Popular Tags |