Example usage for org.springframework.transaction.support TransactionTemplate setIsolationLevel

List of usage examples for org.springframework.transaction.support TransactionTemplate setIsolationLevel

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionTemplate setIsolationLevel.

Prototype

public final void setIsolationLevel(int isolationLevel) 

Source Link

Document

Set the isolation level.

Usage

From source file:fi.hsl.parkandride.core.service.PredictionService.java

private void doUpdatePredictions() {
    log.info("Updating predictions");
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    txTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); // TODO: set in Core/JdbcConfiguration
    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    for (Long predictorId : findPredictorsNeedingUpdate()) {
        try {/* w  ww  .  jav a2s  .  co m*/
            txTemplate.execute(tx -> {
                updatePredictor(predictorId);
                log.debug("Updating predictor {} done", predictorId);
                return null;
            });
        } catch (Exception e) {
            log.error("Failed to update predictor {}", predictorId, e);
        }
    }
}

From source file:net.cpollet.jixture.tests.integration.hibernate3.BaseTestDatabaseTestSupport.java

private void executeInNewTransaction(TransactionCallback transactionCallback) {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);

    transactionTemplate.execute(transactionCallback);
}

From source file:org.springextensions.db4o.Db4oTransactionManagerTest.java

@Test
public void testInvalidIsolation() throws Exception {
    final ExtObjectContainer container = mock(ExtObjectContainer.class);

    PlatformTransactionManager tm = new Db4oTransactionManager(container);
    TransactionTemplate tt = new TransactionTemplate(tm);

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    try {//from   w w w .j  a va  2 s.  co  m
        tt.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(container),
                        "Has thread session");
                Db4oTemplate template = new Db4oTemplate(container);
                template.execute(new Db4oCallback() {
                    public Object doInDb4o(ObjectContainer cont) {
                        return null;
                    }
                });
            }
        });
        Assert.fail("Should have thrown InvalidIsolationLevelException");
    } catch (InvalidIsolationLevelException e) {
        // it's okay
    }

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    // TODO verify(container)....; exception thrown?
}

From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java

@Test
public void testWrongIsolationLevel() {
    final ODB odb = Mockito.mock(ODB.class);
    Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException());
    PlatformTransactionManager tm = new NeoDatisTransactionManager(odb);
    TransactionTemplate tmpl = new TransactionTemplate(tm);

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

    tmpl.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    try {/*  w ww .jav a2s  .  c  o  m*/
        tmpl.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb));
                NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb);
                neoDatisTemplate.store(null);
                transactionStatus.setRollbackOnly();
            }
        });
        Assert.fail("Should throw an exception.");
    } catch (InvalidIsolationLevelException e) {
        // is ok
    }

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

}

From source file:org.ambraproject.struts2.TransactionInterceptor.java

public String intercept(final ActionInvocation actionInvocation) throws Exception {

    final Action action = (Action) actionInvocation.getAction();
    final ActionProxy actionProxy = actionInvocation.getProxy();
    final String methodName = actionProxy.getMethod();

    if (getAnnotation(action.getClass(), methodName, ManualTransactionManagement.class) != null) {
        //Method is annotated tellling us not to manage a transaction for it
        log.debug(/*from  w ww.ja  v  a  2s. co  m*/
                "Not managing transaction for " + action.getClass().getSimpleName() + "." + methodName + "()");
        return actionInvocation.invoke();
    }

    if (log.isDebugEnabled()) {
        log.debug("Intercepted " + action.getClass().getSimpleName() + "." + methodName + "()");
    }

    final Transactional transactionalAnnotation = getAnnotation(action.getClass(), methodName,
            Transactional.class);
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    if (transactionalAnnotation != null) {
        txTemplate.setReadOnly(transactionalAnnotation.readOnly());
        txTemplate.setTimeout(transactionalAnnotation.timeout());
        txTemplate.setIsolationLevel(transactionalAnnotation.isolation().value());
        txTemplate.setPropagationBehavior(transactionalAnnotation.propagation().value());
    }

    CallbackResult callbackResult = (CallbackResult) txTemplate.execute(new TransactionCallback() {
        public CallbackResult doInTransaction(TransactionStatus transactionStatus) {
            CallbackResult result = new CallbackResult();
            try {
                String actionResult = actionInvocation.invoke();
                result.setResult(actionResult);
                //Rollback for Action responses indicating failure
                for (String response : new String[] { Action.ERROR, Action.INPUT, Action.LOGIN }) {
                    if (response.equalsIgnoreCase(actionResult) && !transactionStatus.isRollbackOnly()) {
                        log.debug("Rolling back action " + action.getClass().getSimpleName()
                                + " due to result: " + actionResult);
                        transactionStatus.setRollbackOnly();
                        break;
                    }
                }
            } catch (Exception e) {
                /*
                * Callback does not throw exception. We need to pass Exception object in the return
                * parameter so we can throw it in the calling method.
                */
                boolean noRollback = false;

                if (transactionalAnnotation != null && transactionalAnnotation.noRollbackFor() != null) {
                    for (Class<? extends Throwable> exception : transactionalAnnotation.noRollbackFor()) {
                        if (exception.isInstance(e)) {
                            noRollback = true;
                            break;
                        }
                    }
                }

                if (!noRollback && transactionalAnnotation != null
                        && transactionalAnnotation.rollbackFor() != null) {
                    for (Class<? extends Throwable> exception : transactionalAnnotation.rollbackFor()) {
                        if (exception.isInstance(e)) {
                            log.debug("Caught exception, rolling back action invocation "
                                    + action.getClass().getSimpleName());
                            transactionStatus.setRollbackOnly();
                            break;
                        }
                    }
                }
                result.setException(e);
            }
            return result;
        }
    });

    if (callbackResult.getException() != null)
        throw callbackResult.getException();

    return callbackResult.getResult();
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

@Test
public void testJtaTransactionWithIsolationLevelContentSourceAdapter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

    final IsolationLevelContentSourceAdapter dsToUse = new IsolationLevelContentSourceAdapter();
    dsToUse.setTargetContentSource(contentSource);
    dsToUse.afterPropertiesSet();//  w w  w .  jav a2 s  .c  o  m

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);

    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.setReadOnly(true);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(session).setTransactionMode(Session.TransactionMode.QUERY);
    verify(session, times(2)).close();
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionWithIsolationLevelContentSourceRouter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

    final ContentSource contentSource1 = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    given(contentSource1.newSession()).willReturn(session1);

    final ContentSource contentSource2 = mock(ContentSource.class);
    final Session session2 = mock(Session.class);
    given(contentSource2.newSession()).willReturn(session2);

    final IsolationLevelContentSourceRouter dsToUse = new IsolationLevelContentSourceRouter();
    Map<Object, Object> targetContentSources = new HashMap<Object, Object>();

    targetContentSources.put("ISOLATION_REPEATABLE_READ", contentSource2);
    dsToUse.setDefaultTargetContentSource(contentSource1);

    dsToUse.setTargetContentSources(targetContentSources);
    dsToUse.afterPropertiesSet();/*from w  w  w . ja  v  a2s  . c  om*/

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);

    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session1, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session2, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(session1).close();
    verify(session2).close();
}

From source file:org.springframework.integration.jdbc.store.channel.AbstractTxTimeoutMessageStoreTests.java

public void test() throws InterruptedException {

    int maxMessages = 10;
    int maxWaitTime = 30000;

    final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

    transactionTemplate.setIsolationLevel(Isolation.READ_COMMITTED.value());
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

    for (int i = 1; i <= maxMessages; ++i) {
        final String message = "TEST MESSAGE " + i;
        log.info("Sending message: " + message);

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override/* ww  w  .  j a va 2  s . c o  m*/
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                inputChannel.send(MessageBuilder.withPayload(message).build());
            }
        });

        log.info(String.format("Done sending message %s of %s: %s", i, maxMessages, message));
    }

    log.info("Done sending " + maxMessages + " messages.");

    Assert.assertTrue(String.format("Contdown latch did not count down from " + "%s to 0 in %sms.", maxMessages,
            maxWaitTime), testService.await(maxWaitTime));

    Thread.sleep(2000);

    Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(jdbcChannelMessageStore.getSizeOfIdCache()));
    Assert.assertEquals(Integer.valueOf(maxMessages), Integer.valueOf(testService.getSeenMessages().size()));
    Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(testService.getDuplicateMessagesCount()));
}