Example usage for org.springframework.transaction.support TransactionCallback doInTransaction

List of usage examples for org.springframework.transaction.support TransactionCallback doInTransaction

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionCallback doInTransaction.

Prototype

@Nullable
T doInTransaction(TransactionStatus status);

Source Link

Document

Gets called by TransactionTemplate#execute within a transactional context.

Usage

From source file:net.cpollet.jixture.tests.mocks.TransactionTemplateMock.java

@Override
public <T> T execute(TransactionCallback<T> action) throws TransactionException {
    executed = true;/*from  w  w w.  ja va  2 s .  c om*/
    return action.doInTransaction(null);
}

From source file:net.cpollet.jixture.asserts.TestJixtureAssert.java

@Test
public void transactionTemplateIsUsedWhenSet() {
    // GIVEN//ww w  . j a  va2s .  com
    Mockito.when(unitDao.getAll(User.class)).thenReturn(Collections.<User>emptyList());

    final boolean[] transactionTemplateUsed = { false };
    TransactionTemplate transactionTemplate = new TransactionTemplate() {
        @Override
        public <T> T execute(TransactionCallback<T> action) throws TransactionException {
            transactionTemplateUsed[0] = true;
            return action.doInTransaction(null);
        }
    };

    // WHEN
    JixtureAssert.assertThat(User.class).usingTransactionTemplate(transactionTemplate).isEmpty();

    // THEN
    assertThat(transactionTemplateUsed[0]).isTrue();
}

From source file:org.codehaus.grepo.procedure.repository.GenericProcedureRepositorySupport.java

/**
 * Executes the given {@code callback} with either an read-only, normal or none transaction template.
 *
 * @param callback The callback to execute.
 * @param preferReadOnlyTransactionTemplate Flag to indicate if the read-only template should be prefered.
 * @return Returns the result./*from   w w  w  .j a  v  a  2s . co  m*/
 */
@SuppressWarnings("unchecked")
protected Map<String, Object> executeCallback(TransactionCallback<Object> callback,
        boolean preferReadOnlyTransactionTemplate) {
    boolean isReadOnlyTemplateUsed = false;
    TransactionTemplate templateToUse = null;
    if (preferReadOnlyTransactionTemplate && getReadOnlyTransactionTemplate() != null) {
        isReadOnlyTemplateUsed = true;
        templateToUse = getReadOnlyTransactionTemplate();
    } else {
        templateToUse = getTransactionTemplate();
    }

    Map<String, Object> retVal = null;
    if (templateToUse == null) {
        logger.debug("Executing procedure without using transaction template");
        // execute without transaction...
        retVal = (Map<String, Object>) callback.doInTransaction(null);
    } else {
        logger.debug("Executing procedure using {} transaction template",
                (isReadOnlyTemplateUsed ? "read-only" : ""));
        retVal = (Map<String, Object>) templateToUse.execute(callback);
    }
    return retVal;
}

From source file:org.codehaus.grepo.query.commons.repository.GenericQueryRepositorySupport.java

/**
 * Executes the given {@code callback} with either an read-only, normal or none transaction template.
 *
 * @param callback The callback to execute.
 * @param preferReadOnlyTransactionTemplate Flag to indicate if the read-only template should be prefered.
 * @return Returns the result.//from w  w  w.java2  s  . c  o  m
 */
protected Object executeCallback(TransactionCallback<Object> callback,
        boolean preferReadOnlyTransactionTemplate) {
    boolean isReadOnlyTemplateUsed = false;
    TransactionTemplate templateToUse = null;
    if (preferReadOnlyTransactionTemplate && getReadOnlyTransactionTemplate() != null) {
        isReadOnlyTemplateUsed = true;
        templateToUse = getReadOnlyTransactionTemplate();
    } else {
        templateToUse = getTransactionTemplate();
    }

    Object retVal = null;
    if (templateToUse == null) {
        logger.debug("Executing query without using transaction template");
        // execute without transaction...
        retVal = callback.doInTransaction(null);
    } else {
        logger.debug("Executing query using{}transaction template",
                (isReadOnlyTemplateUsed ? " read-only " : " "));
        retVal = templateToUse.execute(callback);
    }
    return retVal;
}

From source file:nl.strohalm.cyclos.utils.TransactionHelperImpl.java

@Override
public <T> T maybeRunInNewTransaction(final TransactionCallback<T> callback, final boolean newTransaction,
        final LockedAccountsOnPayments minForNewTx) {
    if (newTransaction && applicationService.getLockedAccountsOnPayments().compareTo(minForNewTx) >= 0) {
        return runInNewTransaction(callback);
    } else {/*from   ww  w .  ja va 2s  .co  m*/
        return callback.doInTransaction(null);
    }
}

From source file:nl.strohalm.cyclos.utils.TransactionHelperImpl.java

private <T> RunResult<T> runInCurrentThreadWithResult(final TransactionCallback<T> callback,
        final boolean runTransactional) {
    RunResult<T> result;/*from   w w  w  .  j av a 2s. co  m*/
    while (true) {
        try {
            result = transactionTemplate.execute(new TransactionCallback<RunResult<T>>() {
                @Override
                public RunResult<T> doInTransaction(final TransactionStatus status) {
                    final RunResult<T> result = new RunResult<T>();
                    try {
                        // Run the callback in transaction
                        result.result = callback.doInTransaction(status);
                        // If got to this point, there were no errors. Commit depends on the status
                        result.commit = !status.isRollbackOnly();
                    } catch (final LockingException e) {
                        // On locking exceptions, we have to retry
                        status.setRollbackOnly();
                        result.retry = true;
                    } catch (final ApplicationException e) {
                        // ApplicationExceptions controls whether rollbacks are done
                        if (e.isShouldRollback()) {
                            status.setRollbackOnly();
                        } else {
                            result.commit = true;
                        }
                        result.error = e;
                    } catch (final Throwable e) {
                        // On any other exception, rollback
                        status.setRollbackOnly();
                        result.error = e;
                    }
                    return result;
                }
            });
        } catch (Throwable t) {
            result = new RunResult<T>();
            if (ExceptionHelper.isLockingException(t)) {
                result.retry = true;
            } else {
                result.error = t;
            }
        }
        // Run the transaction commit / rollback listeners
        CurrentTransactionData.detachListeners().runListeners(result.commit);
        CurrentTransactionData.cleanup();
        if (!result.retry) {
            // No retry is needed - break the loop
            break;
        }
    }

    // If the callback is a Transactional, we should invoke the afterCommit() method on commit
    if (runTransactional) {
        result.maybeRunAfterCommit(callback);
    }
    return result;
}

From source file:org.openvpms.web.component.im.edit.SaveHelper.java

/**
 * Saves an editor and invokes a callback within a single transaction.
 *
 * @param editor   the editor//w ww. j  av  a2 s.  c  om
 * @param callback the callback
 * @return {@code true} if the object was saved and the callback returned {@code true}
 */
public static boolean save(final IMObjectEditor editor, final TransactionCallback<Boolean> callback) {
    Boolean result = null;
    try {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        result = template.execute(new TransactionCallback<Boolean>() {
            public Boolean doInTransaction(TransactionStatus status) {
                boolean result = false;
                if (editor.save()) {
                    Boolean success = callback.doInTransaction(status);
                    result = success != null && success;
                }
                return result;
            }
        });
    } catch (Throwable exception) {
        error(editor, exception);
    }
    return (result != null) && result;
}

From source file:org.springframework.transaction.support.TransactionTemplate.java

@Override
@Nullable/*from   w w w.  ja va 2 s  .c  om*/
public <T> T execute(TransactionCallback<T> action) throws TransactionException {
    Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");

    if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
        return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
    } else {
        TransactionStatus status = this.transactionManager.getTransaction(this);
        T result;
        try {
            result = action.doInTransaction(status);
        } catch (RuntimeException | Error ex) {
            // Transactional code threw application exception -> rollback
            rollbackOnException(status, ex);
            throw ex;
        } catch (Throwable ex) {
            // Transactional code threw unexpected exception -> rollback
            rollbackOnException(status, ex);
            throw new UndeclaredThrowableException(ex,
                    "TransactionCallback threw undeclared checked exception");
        }
        this.transactionManager.commit(status);
        return result;
    }
}