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

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

Introduction

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

Prototype

public TransactionTemplate(PlatformTransactionManager transactionManager) 

Source Link

Document

Construct a new TransactionTemplate using the given transaction manager.

Usage

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

/**
 * Saves an editor in a transaction.//from  w  w  w.  ja  va 2s .  com
 *
 * @param editor the editor to save
 * @return {@code true} if the object was saved successfully
 */
public static boolean save(final IMObjectEditor editor) {
    Boolean result = null;
    try {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        result = template.execute(new TransactionCallback<Boolean>() {
            public Boolean doInTransaction(TransactionStatus status) {
                return editor.save();
            }
        });
    } catch (Throwable exception) {
        error(editor, exception);
    }
    return (result != null) && 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/*from ww w  .  ja  va2  s .  c  o  m*/
 * @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.openvpms.web.component.im.edit.SaveHelper.java

/**
 * Invokes a callback to save objects./*  ww  w .jav a2 s  .c o m*/
 *
 * @param displayName the primary display name, for error reporting
 * @param callback    the callback to execute
 * @return {@code true} if the save was successful
 */
public static boolean save(String displayName, TransactionCallback<Boolean> callback) {
    boolean saved = false;
    try {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        Boolean result = template.execute(callback);
        saved = (result != null) && result;
    } catch (Throwable exception) {
        error(displayName, null, exception);
    }
    return saved;
}

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

/**
 * Replace an object, by deleting one instance and inserting another.
 *
 * @param delete the object to delete/* ww w.ja  va  2 s. co  m*/
 * @param insert the object to insert
 * @return {@code true} if the operation was successful
 */
public static boolean replace(final IMObject delete, final IMObject insert) {
    Boolean result = null;
    try {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        result = template.execute(new TransactionCallback<Boolean>() {
            public Boolean doInTransaction(TransactionStatus status) {
                IArchetypeService service = ServiceHelper.getArchetypeService();
                service.remove(delete);
                service.save(insert);
                return true;
            }
        });
    } catch (Throwable exception) {
        String title = Messages.get("imobject.replace.failed.title");
        ErrorHelper.show(title, exception);
    }
    return (result != null) && result;
}

From source file:org.openvpms.web.workspace.admin.lookup.LookupReplaceHelper.java

/**
 * Replaces references to the source lookup with the target lookup, optionally deleting the source lookup.
 *
 * @param source the source lookup/* w w w.  j  av a2  s  .c om*/
 * @param target the target lookup
 * @param delete if <tt>true</tt> delete the source lookup
 */
public void replace(final Lookup source, final Lookup target, final boolean delete) {
    TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            doReplace(source, target, delete);
            return null;
        }
    });
}

From source file:org.openvpms.web.workspace.patient.PatientMedicalRecordLinker.java

/**
 * Links the records./*  w  ww .  j ava  2  s  . co  m*/
 *
 * @param currentEvent   the current instance of the event. May be {@code null}
 * @param currentProblem the current instance of the problem. May be {@code null}
 * @param currentItem    the current instance of the item. May be {@code null}
 * @return {@code true} if the records were linked, {@code false} if an act is no longer available
 */
private boolean linkRecords(final Act currentEvent, final Act currentProblem, final Act currentItem) {
    boolean result = false;
    if (currentEvent == null && event != null) {
        logMissing(event);
    } else if (currentProblem == null && problem != null) {
        logMissing(problem);
    } else if (currentItem == null && item != null) {
        logMissing(item);
    } else {
        TransactionTemplate template = new TransactionTemplate(ServiceHelper.getTransactionManager());
        template.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                link(currentEvent, currentProblem, currentItem);
            }
        });
        this.currentEvent = currentEvent;
        this.currentProblem = currentProblem;
        this.currentItem = currentItem;
        result = true;
    }
    return result;
}

From source file:org.pentaho.aggdes.ui.exec.impl.JdbcTemplateSqlExecutor.java

public void execute(final String[] sql, final ExecutorCallback callback) throws DataAccessException {
    Exception exceptionDuringExecute = null;
    DatabaseMeta dbMeta = connectionModel.getDatabaseMeta();
    String url = null;//from  ww  w  .ja  v a 2  s . c o  m
    try {
        url = dbMeta.getURL();
    } catch (KettleDatabaseException e) {
        throw new DataAccessException("DatabaseMeta problem", e) {
            private static final long serialVersionUID = -3457360074729938909L;
        };
    }
    // create the datasource
    DataSource ds = new SingleConnectionDataSource(dbMeta.getDriverClass(), url, dbMeta.getUsername(),
            dbMeta.getPassword(), false);

    // create the jdbc template
    final JdbcTemplate jt = new JdbcTemplate(ds);

    // create the transaction manager
    DataSourceTransactionManager tsMan = new DataSourceTransactionManager(ds);

    // create the transaction template
    TransactionTemplate txTemplate = new TransactionTemplate(tsMan);

    // set behavior
    txTemplate.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
    final String noCommentSql[] = removeCommentsAndSemicolons(connectionModel.getSchema(), sql);
    try {
        // run the code in a transaction
        txTemplate.execute(new TransactionCallbackWithoutResult() {
            public void doInTransactionWithoutResult(TransactionStatus status) {
                jt.batchUpdate(noCommentSql);
            }
        });
    } catch (DataAccessException e) {
        if (logger.isErrorEnabled()) {
            logger.error("data access exception", e);
        }
        exceptionDuringExecute = e;
    }
    callback.executionComplete(exceptionDuringExecute);

}

From source file:org.projectforge.core.HibernateSearchReindexer.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void reindex(final Class<?> clazz, final ReindexSettings settings, final StringBuffer buf) {
    // PF-378: Performance of run of full re-indexing the data-base is very slow for large data-bases
    // Single transactions needed, otherwise the full run will be very slow for large data-bases.
    final TransactionTemplate tx = new TransactionTemplate(
            new HibernateTransactionManager(hibernate.getSessionFactory()));
    tx.execute(new TransactionCallback() {
        // The call-back is needed, otherwise a lot of transactions are left open until last run is completed:
        public Object doInTransaction(final TransactionStatus status) {
            try {
                hibernate.execute(new HibernateCallback() {
                    public Object doInHibernate(final Session session) throws HibernateException {
                        databaseDao.reindex(clazz, settings, buf);
                        status.setRollbackOnly();
                        return null;
                    }/*w  w w.  j  a  va 2 s .c om*/
                });
            } catch (final Exception ex) {
                buf.append(" (an error occured, see log file for further information.), ");
                log.error("While rebuilding data-base-search-index for '" + clazz.getName() + "': "
                        + ex.getMessage(), ex);
            }
            return null;
        }
    });
}

From source file:org.projectforge.database.xstream.HibernateXmlConverter.java

/**
 * Schreibt alle Objekte der Datenbank in den angegebenen Writer.<br/>
 * <b>Warnung!</b> Bei der Serialisierung von Collections wird derzeit nur {@link java.util.Set} sauber untersttzt.
 * @param writer Ziel fr die XML-Datei.//from  w  w w.  j  av a 2  s  . co  m
 * @param includeHistory bei false werden die History Eintrge nicht geschrieben
 * @param preserveIds If true, the object ids will be preserved, otherwise new ids will be assigned through xstream.
 */
public void dumpDatabaseToXml(final Writer writer, final boolean includeHistory, final boolean preserveIds) {
    final TransactionTemplate tx = new TransactionTemplate(
            new HibernateTransactionManager(hibernate.getSessionFactory()));
    tx.execute(new TransactionCallback() {
        public Object doInTransaction(final TransactionStatus status) {
            hibernate.execute(new HibernateCallback() {
                public Object doInHibernate(final Session session) throws HibernateException {
                    writeObjects(writer, includeHistory, session, preserveIds);
                    status.setRollbackOnly();
                    return null;
                }
            });
            return null;
        }
    });
}

From source file:org.projectforge.framework.persistence.history.HibernateSearchReindexer.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void reindex(final Class<?> clazz, final ReindexSettings settings, final StringBuffer buf) {
    // PF-378: Performance of run of full re-indexing the data-base is very slow for large data-bases
    // Single transactions needed, otherwise the full run will be very slow for large data-bases.
    final TransactionTemplate tx = new TransactionTemplate(
            new HibernateTransactionManager(hibernate.getSessionFactory()));
    tx.execute(new TransactionCallback() {
        // The call-back is needed, otherwise a lot of transactions are left open until last run is completed:
        @Override/*from ww  w.  ja  v  a2s  .  c o m*/
        public Object doInTransaction(final TransactionStatus status) {
            try {
                hibernate.execute(new HibernateCallback() {
                    @Override
                    public Object doInHibernate(final Session session) throws HibernateException {
                        databaseDao.reindex(clazz, settings, buf);
                        status.setRollbackOnly();
                        return null;
                    }
                });
            } catch (final Exception ex) {
                buf.append(" (an error occured, see log file for further information.), ");
                log.error("While rebuilding data-base-search-index for '" + clazz.getName() + "': "
                        + ex.getMessage(), ex);
            }
            return null;
        }
    });
}