Search in sources :

Example 21 with EntityTransaction

use of javax.persistence.EntityTransaction in project wildfly by wildfly.

the class SFSB1 method createEmployeeNoJTATransaction.

@TransactionAttribute(TransactionAttributeType.NEVER)
public void createEmployeeNoJTATransaction(String name, String address, int id) {
    EntityManager em = emf.createEntityManager();
    Employee emp = new Employee();
    emp.setId(id);
    emp.setAddress(address);
    emp.setName(name);
    EntityTransaction tx1 = em.getTransaction();
    try {
        tx1.begin();
        em.joinTransaction();
        em.persist(emp);
        tx1.commit();
    } catch (Exception e) {
        throw new RuntimeException("couldn't start tx", e);
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) TransactionAttribute(javax.ejb.TransactionAttribute)

Example 22 with EntityTransaction

use of javax.persistence.EntityTransaction in project deltaspike by apache.

the class ResourceLocalTransactionStrategy method execute.

@Override
public Object execute(InvocationContext invocationContext) throws Exception {
    Transactional transactionalAnnotation = transactionHelper.extractTransactionalAnnotation(invocationContext);
    //see DELTASPIKE-517
    Class targetClass = ProxyUtils.getUnproxiedClass(invocationContext.getTarget().getClass());
    // all the configured qualifier keys
    Set<Class<? extends Annotation>> emQualifiers = emHolder.isSet() ? new HashSet<Class<? extends Annotation>>(Arrays.asList(Default.class)) : transactionHelper.resolveEntityManagerQualifiers(transactionalAnnotation, targetClass);
    TransactionBeanStorage transactionBeanStorage = TransactionBeanStorage.getInstance();
    boolean isOutermostInterceptor = transactionBeanStorage.isEmpty();
    boolean outermostTransactionAlreadyExisted = false;
    if (isOutermostInterceptor) {
        // a new Context needs to get started
        transactionBeanStorage.startTransactionScope();
    }
    // the 'layer' of the transactional invocation, aka the refCounter
    @SuppressWarnings("UnusedDeclaration") int transactionLayer = transactionBeanStorage.incrementRefCounter();
    Exception firstException = null;
    try {
        for (Class<? extends Annotation> emQualifier : emQualifiers) {
            EntityManager entityManager = resolveEntityManagerForQualifier(emQualifier);
            EntityManagerEntry entityManagerEntry = createEntityManagerEntry(entityManager, emQualifier);
            transactionBeanStorage.storeUsedEntityManager(entityManagerEntry);
            EntityTransaction transaction = getTransaction(entityManagerEntry);
            if (!transaction.isActive()) {
                beforeBegin(invocationContext, entityManagerEntry, transaction);
                transaction.begin();
            } else if (isOutermostInterceptor) {
                outermostTransactionAlreadyExisted = true;
            }
            //don't move it before EntityTransaction#begin() and invoke it in any case
            beforeProceed(invocationContext, entityManagerEntry, transaction);
        }
        return invocationContext.proceed();
    } catch (Exception e) {
        firstException = e;
        // this way, we allow inner functions to catch and handle exceptions properly.
        if (isOutermostInterceptor) {
            Set<EntityManagerEntry> entityManagerEntryList = transactionBeanStorage.getUsedEntityManagerEntries();
            if (!outermostTransactionAlreadyExisted) {
                // We only commit transactions we opened ourselfs.
                // If the transaction got opened outside of our interceptor chain
                // we must not handle it.
                // This e.g. happens if a Stateless EJB invokes a Transactional CDI bean
                // which uses the BeanManagedUserTransactionStrategy.
                rollbackAllTransactions(entityManagerEntryList);
            }
            // drop all EntityManagers from the request-context cache
            transactionBeanStorage.cleanUsedEntityManagers();
        }
        // give any extensions a chance to supply a better error message
        e = prepareException(e);
        // rethrow the exception
        throw e;
    } finally {
        // will get set if we got an Exception while committing
        // in this case, we rollback all later transactions too.
        boolean commitFailed = false;
        // In case of JTA we will just commit the UserTransaction.
        if (isOutermostInterceptor) {
            if (!outermostTransactionAlreadyExisted) {
                if (firstException == null) {
                    // only commit all transactions if we didn't rollback
                    // them already
                    Set<EntityManagerEntry> entityManagerEntryList = transactionBeanStorage.getUsedEntityManagerEntries();
                    boolean rollbackOnly = isRollbackOnly(transactionalAnnotation);
                    if (!rollbackOnly && entityManagerEntryList.size() > 1) {
                        // but first try to flush all the transactions and write the updates to the database
                        for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) {
                            EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
                            if (transaction != null && transaction.isActive()) {
                                try {
                                    if (!commitFailed) {
                                        currentEntityManagerEntry.getEntityManager().flush();
                                        if (!rollbackOnly && transaction.getRollbackOnly()) {
                                            // don't set commitFailed to true directly
                                            // (the order of the entity-managers isn't deterministic
                                            //  -> tests would break)
                                            rollbackOnly = true;
                                        }
                                    }
                                } catch (Exception e) {
                                    firstException = e;
                                    commitFailed = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (rollbackOnly) {
                        commitFailed = true;
                    }
                    // and now either commit or rollback all transactions
                    for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) {
                        EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
                        if (transaction != null && transaction.isActive()) {
                            try {
                                // last chance to check it (again)
                                if (commitFailed || transaction.getRollbackOnly()) {
                                    beforeRollback(invocationContext, currentEntityManagerEntry, transaction);
                                    transaction.rollback();
                                } else {
                                    beforeCommit(invocationContext, currentEntityManagerEntry, transaction);
                                    transaction.commit();
                                }
                            } catch (Exception e) {
                                firstException = e;
                                commitFailed = true;
                            } finally {
                                afterProceed(invocationContext, currentEntityManagerEntry, firstException);
                            }
                        }
                    }
                }
            }
            // and now we close the open transaction scope
            transactionBeanStorage.endTransactionScope();
            onCloseTransactionScope();
        }
        transactionBeanStorage.decrementRefCounter();
        if (commitFailed && firstException != null) /*null if just #getRollbackOnly is true*/
        {
            throwException(firstException);
        }
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Set(java.util.Set) HashSet(java.util.HashSet) TransactionBeanStorage(org.apache.deltaspike.jpa.impl.transaction.context.TransactionBeanStorage) Annotation(java.lang.annotation.Annotation) EntityManager(javax.persistence.EntityManager) EntityManagerEntry(org.apache.deltaspike.jpa.impl.transaction.context.EntityManagerEntry) Transactional(org.apache.deltaspike.jpa.api.transaction.Transactional)

Example 23 with EntityTransaction

use of javax.persistence.EntityTransaction in project spring-framework by spring-projects.

the class DefaultJpaDialectTests method testDefaultBeginTransaction.

@Test
public void testDefaultBeginTransaction() throws Exception {
    TransactionDefinition definition = new DefaultTransactionDefinition();
    EntityManager entityManager = mock(EntityManager.class);
    EntityTransaction entityTx = mock(EntityTransaction.class);
    given(entityManager.getTransaction()).willReturn(entityTx);
    dialect.beginTransaction(entityManager, definition);
}
Also used : TransactionDefinition(org.springframework.transaction.TransactionDefinition) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) Test(org.junit.Test)

Example 24 with EntityTransaction

use of javax.persistence.EntityTransaction in project spring-framework by spring-projects.

the class JpaTransactionManagerTests method testTransactionWithRequiresNewInAfterCompletion.

@Test
public void testTransactionWithRequiresNewInAfterCompletion() {
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    EntityManager manager2 = mock(EntityManager.class);
    EntityTransaction tx2 = mock(EntityTransaction.class);
    given(manager.getTransaction()).willReturn(tx);
    given(factory.createEntityManager()).willReturn(manager, manager2);
    given(manager2.getTransaction()).willReturn(tx2);
    given(manager2.isOpen()).willReturn(true);
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

                @Override
                public void afterCompletion(int status) {
                    tt.execute(new TransactionCallback() {

                        @Override
                        public Object doInTransaction(TransactionStatus status) {
                            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
                            return null;
                        }
                    });
                }
            });
            return null;
        }
    });
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    verify(tx).commit();
    verify(tx2).begin();
    verify(tx2).commit();
    verify(manager).flush();
    verify(manager).close();
    verify(manager2).flush();
    verify(manager2).close();
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) TransactionCallback(org.springframework.transaction.support.TransactionCallback) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionSynchronizationAdapter(org.springframework.transaction.support.TransactionSynchronizationAdapter) Test(org.junit.Test)

Example 25 with EntityTransaction

use of javax.persistence.EntityTransaction in project spring-framework by spring-projects.

the class JpaTransactionManager method doCommit.

@Override
protected void doCommit(DefaultTransactionStatus status) {
    JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Committing JPA transaction on EntityManager [" + txObject.getEntityManagerHolder().getEntityManager() + "]");
    }
    try {
        EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
        tx.commit();
    } catch (RollbackException ex) {
        if (ex.getCause() instanceof RuntimeException) {
            DataAccessException dex = getJpaDialect().translateExceptionIfPossible((RuntimeException) ex.getCause());
            if (dex != null) {
                throw dex;
            }
        }
        throw new TransactionSystemException("Could not commit JPA transaction", ex);
    } catch (RuntimeException ex) {
        // Assumably failed to flush changes to database.
        throw DataAccessUtils.translateIfNecessary(ex, getJpaDialect());
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) TransactionSystemException(org.springframework.transaction.TransactionSystemException) RollbackException(javax.persistence.RollbackException) DataAccessException(org.springframework.dao.DataAccessException)

Aggregations

EntityTransaction (javax.persistence.EntityTransaction)59 EntityManager (javax.persistence.EntityManager)38 Test (org.junit.Test)12 EntityManagerFactory (javax.persistence.EntityManagerFactory)9 Query (javax.persistence.Query)8 UserTestDbo (org.webpieces.plugins.hibernate.app.dbo.UserTestDbo)6 InumSqlEntry (org.gluu.oxtrust.model.sql.InumSqlEntry)4 Person (org.hibernate.userguide.model.Person)3 TransactionStatus (org.springframework.transaction.TransactionStatus)3 Transactional (com.google.inject.persist.Transactional)2 Priority (org.hibernate.envers.test.Priority)2 DefaultTransactionAttribute (org.springframework.transaction.interceptor.DefaultTransactionAttribute)2 UserDbo (WEBPIECESxPACKAGE.base.libs.UserDbo)1 UserRole (WEBPIECESxPACKAGE.base.libs.UserRole)1 FileType (aserg.gtf.model.FileType)1 Annotation (java.lang.annotation.Annotation)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1