1 package org.collectionspace.services.common.storage.jpa;
3 import javax.persistence.EntityManager;
4 import javax.persistence.EntityManagerFactory;
5 import javax.persistence.Query;
7 import org.collectionspace.services.common.context.ServiceContext;
8 import org.collectionspace.services.common.document.TransactionException;
9 import org.collectionspace.services.common.storage.TransactionContext;
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
13 @SuppressWarnings("rawtypes")
14 public class JPATransactionContext extends TransactionContext {
16 private final Logger logger = LoggerFactory.getLogger(TransactionContext.class);
18 private int transactionRefCount = 0;
19 private Boolean commitSuccessful = null;
21 EntityManagerFactory emf;
24 public JPATransactionContext(ServiceContext ctx) {
25 emf = JpaStorageUtils.getEntityManagerFactory();
26 em = emf.createEntityManager();
30 public JPATransactionContext() {
31 emf = JpaStorageUtils.getEntityManagerFactory();
32 em = emf.createEntityManager();
35 protected EntityManagerFactory getEntityManagerFactory() {
39 protected EntityManager getEntityManager() {
44 public ServiceContext getServiceContext() {
49 public void markForRollback() {
50 if (em.getTransaction().isActive() == true) {
51 em.getTransaction().setRollbackOnly();
53 String msg = "Attemped to mark an inactive transaction for rollback.";
59 public void close() throws TransactionException {
60 if (em.getTransaction().isActive() == true && em.getTransaction().getRollbackOnly() == true) {
61 em.getTransaction().rollback();
62 } else if (em.getTransaction().isActive() == true) {
63 throw new JPATransactionException("There is an active transaction. You must commit the active transaction prior to calling this close method.");
67 JpaStorageUtils.releaseEntityManagerFactory(emf);
71 synchronized public void beginTransaction() {
72 if (transactionRefCount == 0) {
73 em.getTransaction().begin();
75 transactionRefCount++;
79 public void persist(Object entity) {
84 public Object find(Class entityClass, Object primaryKey) {
85 return em.find(entityClass, primaryKey);
89 public Object find(Class entityClass, String id) {
90 return em.find(entityClass, id);
94 public Query createQuery(String qlString) {
95 return em.createQuery(qlString);
99 public void remove(Object entity) {
104 public void commitTransaction() throws TransactionException {
105 if (transactionRefCount == 0) {
106 throw new JPATransactionException("There is no active transaction to commit.");
108 if (--transactionRefCount == 0) {
109 em.getTransaction().commit();
110 commitSuccessful = Boolean.TRUE;
115 public boolean isTransactionActive() {
116 return em.getTransaction().isActive();