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

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

Introduction

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

Prototype

@Override
    @Nullable
    public <T> T execute(TransactionCallback<T> action) throws TransactionException 

Source Link

Usage

From source file:com.github.ferstl.spring.jdbc.oracle.DatabaseConfiguration.java

private void initDatabase(final JdbcTemplate jdbcTemplate) {
    TransactionTemplate trxTemplate = new TransactionTemplate(transactionManager());
    trxTemplate.execute(new TransactionCallback<int[]>() {

        @Override//from   www. j  a va 2  s. c om
        public int[] doInTransaction(TransactionStatus status) {
            List<Object[]> batchArgs = new ArrayList<>(NUMBER_OF_ROWS);
            for (int i = 0; i < NUMBER_OF_ROWS; i++) {
                int value = i + 1;
                batchArgs.add(new Object[] { String.format("Value_%05d", value), value });
            }
            return jdbcTemplate.batchUpdate(INSERT_SQL, batchArgs);
        }
    });
}

From source file:net.chrisrichardson.foodToGo.restaurantNotificationService.tsImpl.dao.OrderDAOIBatisImplTests.java

public void testFindOrdersToSend_pessimistic() throws Exception {
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
    TransactionTemplate tt = new TransactionTemplate(tm);

    // This has to be done in a transaction

    tt.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            dao.setLockingMode(OrderDAOIBatisImpl.PESSIMISTIC_LOCKING);
            List orders = dao.findOrdersToSend();
            assertFalse(orders.isEmpty());
            return null;
        }/* w  ww .  jav  a 2  s  .c  om*/
    });
}

From source file:mojo.core.test.XStreamTest.java

public void testProxy() {
    log("Testing uninitialized hibernate collection");
    Object tmp = personService.findById(person.getId());
    String xml = xstream.toXML(tmp);
    // System.out.println("XML: " + xml);
    assertEmptyElement(xml, "pets");
    assertEmptyElement(xml, "phones");

    log("Testing uninitialized hibernate proxy");
    tmp = petService.findById(pet.getId());
    xml = xstream.toXML(tmp);/*  ww  w  .  jav  a 2  s .com*/
    // System.out.println("XML: " + xml);
    assertEmptyElement(xml, "owner");

    log("Testing initialized hibernate proxy & collection");
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    tmp = template.execute(new TransactionCallback<Object>() {

        public Object doInTransaction(TransactionStatus status) {
            Select<Object> query = new Select<Object>(Pet.class, new ByKey(pet.getId()));
            Pet pet = (Pet) repository.select(query).unique();
            pet.getOwner().getName(); // init proxy
            pet.getOwner().getPets().size(); // init collection
            return pet;
        }
    });

    xml = xstream.toXML(tmp);
    // System.out.println("XML: " + xml);
    assertNotEmptyElement(xml, "owner");
    assertNotEmptyElement(xml, "pets");
    assertEmptyElement(xml, "phones");
}

From source file:org.dalesbred.integration.spring.SpringTransactionManager.java

private <T> T execute(@NotNull TransactionCallback<T> callback, @NotNull Dialect dialect,
        @NotNull DefaultTransactionDefinition df) {
    TransactionTemplate tt = new TransactionTemplate(platformTransactionManager, df);
    return tt.execute(status -> {
        try {/*  w w w .j  a v a 2 s.c om*/
            Connection connection = DataSourceUtils.getConnection(dataSource);
            try {
                return callback.execute(new SpringTransactionContext(status, connection));
            } finally {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        } catch (SQLException e) {
            throw dialect.convertException(e);
        }
    });
}

From source file:org.activiti.spring.SpringTransactionInterceptor.java

@SuppressWarnings("unchecked")
public <T> T execute(final Command<T> command) {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(transactionPropagation);
    T result = (T) transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            return next.execute(command);
        }//from  www  .j a v  a  2s  .  co m
    });
    return result;
}

From source file:org.openmrs.module.imbmetadata.deploy.bundle.ImbMetadataBundle.java

/**
 * Setting multiple GPs is much faster in a single transaction
 *///w ww  .j a  va 2s  . c om
protected void setGlobalProperties(final Map<String, String> properties) {
    TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                setGlobalProperty(entry.getKey(), entry.getValue());
            }
        }
    });
}

From source file:ca.uhn.fhir.jpa.search.StaleSearchDeletingSvc.java

@Scheduled(fixedDelay = 10 * DateUtils.MILLIS_PER_SECOND)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public synchronized void pollForStaleSearches() {
    Date cutoff = new Date(System.currentTimeMillis() - myDaoConfig.getExpireSearchResultsAfterMillis());
    ourLog.debug("Searching for searches which are before {}", cutoff);

    Collection<Search> toDelete = mySearchDao.findWhereCreatedBefore(cutoff);
    if (toDelete.isEmpty()) {
        return;//from   w w w . jav  a  2  s.c  om
    }

    TransactionTemplate tt = new TransactionTemplate(myTransactionManager);
    for (final Search next : toDelete) {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus theArg0) {
                Search searchToDelete = mySearchDao.findOne(next.getId());
                ourLog.info("Expiring stale search {} / {}", searchToDelete.getId(), searchToDelete.getUuid());
                mySearchIncludeDao.deleteForSearch(searchToDelete.getId());
                mySearchResultDao.deleteForSearch(searchToDelete.getId());
                mySearchDao.delete(searchToDelete);
            }
        });
    }

    ourLog.info("Deleted {} searches, {} remaining", toDelete.size(), mySearchDao.count());

}

From source file:ar.com.zauber.commons.spring.web.handlers.TransactionAwareHandlerAdapter.java

/** @see HandlerAdapter#handle(
 *       HttpServletRequest, HttpServletResponse, Object) */
public final ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws Exception {

    final TransactionTemplate transactionTemplate = transactionStrategy.getTransactionTemplate(handler,
            request);/*from  w  w w.jav a  2 s  .  com*/

    return transactionTemplate.execute(new TransactionCallback<ModelAndView>() {
        public ModelAndView doInTransaction(final TransactionStatus transactionStatus) {
            // CHECKSTYLE:ALL:OFF
            try {
                return target.handle(request, response, handler);
            } catch (final RuntimeException e) {
                //rollback & re-throw original exception
                transactionStatus.setRollbackOnly();
                throw e;
            } catch (final Exception e) {
                //rollback & wrap original exception
                transactionStatus.setRollbackOnly();
                throw new RuntimeException("Transaction can not be executed", e);
            }
            // CHECKSTYLE:ALL:ON
        }
    });
}

From source file:com.dinstone.jtds.programmatic.ProgrammaticTransactionServiceComponent.java

public void updateUserInfo(final UserInfo user) throws Exception {
    TransactionTemplate transactionTemplate = new TransactionTemplate(txManager);
    transactionTemplate.setName("ProgrammaticTransactionService");

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override/*  w w w .  ja  va2  s  .com*/
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            doUpdate(user);
            findUserInfo(user);
            deException(user);
        }

    });

}

From source file:org.brekka.pegasus.core.services.impl.DownloadServiceImpl.java

@Override
public InputStream download(final AllocationFile file, final ProgressCallback progressCallback,
        final boolean captureDownloadEvent, final boolean incrementCounter) {
    // Has its own transaction
    final FileDownloadEvent event = captureDownloadEvent ? eventService.beginFileDownloadEvent(file) : null;

    // Perform in its own readonly transaction. This ensures that the thread is only using one connection at a time.
    TransactionTemplate tt = new TransactionTemplate(transactionManager);
    tt.setReadOnly(true);//from   w  ww .j  a v a2s .  c o  m
    return tt.execute(new TransactionCallback<EventInputStream>() {
        @Override
        public EventInputStream doInTransaction(final TransactionStatus status) {
            FileType fileType = file.getXml();
            CryptedFile cryptedFile = pavewayService.retrieveCryptedFileById(file.getCryptedFile().getId());
            CryptoProfile cryptoProfile = cryptoProfileService.retrieveProfile(cryptedFile.getProfile());
            SecretKey secretKey = symmetricCryptoService.toSecretKey(fileType.getKey(), cryptoProfile);
            cryptedFile.setSecretKey(secretKey);
            InputStream is = pavewayService.download(cryptedFile);
            return new EventInputStream(is, file, event, cryptedFile.getOriginalLength(), progressCallback,
                    incrementCounter);
        }
    });
}