1 19 package org.apache.cayenne.jpa; 20 21 import java.sql.SQLException ; 22 23 import javax.persistence.EntityManager; 24 import javax.persistence.EntityTransaction; 25 import javax.persistence.PersistenceException; 26 27 import org.apache.cayenne.CayenneException; 28 import org.apache.cayenne.access.Transaction; 29 30 34 public class JpaTransaction implements EntityTransaction { 35 36 protected EntityManager entityManager; 37 protected Transaction transaction; 38 protected boolean rollbackOnly; 39 40 public JpaTransaction(Transaction transaction, EntityManager entityManager) { 41 this.entityManager = entityManager; 42 this.transaction = transaction; 43 } 44 45 50 public void begin() { 51 if (isActive()) { 52 throw new IllegalStateException ("transaction active"); 53 } 54 55 transaction.begin(); 56 } 57 58 64 public void commit() { 65 if (!isActive()) { 66 throw new IllegalStateException ("transaction not active"); 67 } 68 69 try { 70 entityManager.flush(); 71 transaction.commit(); 72 } 73 catch (SQLException e) { 74 throw new PersistenceException(e.getMessage(), e); 75 } 76 catch (CayenneException e) { 77 throw new PersistenceException(e.getMessage(), e); 78 } 79 } 80 81 87 public void rollback() { 88 if (!isActive()) { 89 throw new IllegalStateException ("transaction not active"); 90 } 91 92 try { 93 transaction.rollback(); 94 } 95 catch (SQLException e) { 96 throw new PersistenceException(e.getMessage(), e); 97 } 98 catch (CayenneException e) { 99 throw new PersistenceException(e.getMessage(), e); 100 } 101 } 102 103 108 public boolean isActive() { 109 return (transaction.getStatus() == Transaction.STATUS_ACTIVE); 110 } 111 112 public boolean getRollbackOnly() { 113 return rollbackOnly; 114 } 115 116 public void setRollbackOnly() { 117 rollbackOnly = true; 118 } 119 } 120 | Popular Tags |