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:app.web.AbstractCrudController.java

@RequestMapping(value = "/delete") // TODO: , method = RequestMethod.POST)
public String delete(@RequestParam final int id) {
    new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
            Db.delete(getTypeClass(), id);
        }/*  w w w.  j a va  2s.  c  o  m*/
    });
    return "redirect:.";
}

From source file:org.openremote.beehive.configuration.www.ControllerConfigurationsAPI.java

@POST
public Response createControllerConfiguration(final ControllerConfigurationDTOIn configurationDTO) {

    if (account.getControllerConfigurationByName(configurationDTO.getName()) != null) {
        return Response.status(Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "A controller configuration with the same name already exists"))
                .build();/*from  w  w w  .  j  av a  2s  .  c  o m*/
    }

    return Response.ok(new ControllerConfigurationDTOOut(new TransactionTemplate(platformTransactionManager)
            .execute(new TransactionCallback<ControllerConfiguration>() {
                @Override
                public ControllerConfiguration doInTransaction(TransactionStatus transactionStatus) {
                    ControllerConfiguration newConfiguration = new ControllerConfiguration();
                    newConfiguration.setCategory(configurationDTO.getCategory());
                    newConfiguration.setName(configurationDTO.getName());
                    newConfiguration.setValue(configurationDTO.getValue());
                    account.addControllerConfiguration(newConfiguration);
                    controllerConfigurationRepository.save(newConfiguration);
                    return newConfiguration;
                }
            }))).build();
}

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

private void prepareDatabase() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("prepare-database.sql"));
    populator.setIgnoreFailedDrops(true);

    TransactionTemplate trxTemplate = new TransactionTemplate(transactionManager());
    trxTemplate.execute(new TransactionCallback<Void>() {

        @Override/*from w ww .j a v  a  2s.  c  o m*/
        public Void doInTransaction(TransactionStatus status) {
            DatabasePopulatorUtils.execute(populator, DatabaseConfiguration.this.dataSource);
            return null;
        }
    });
}

From source file:com.mothsoft.alexis.engine.numeric.President2012DataSetImporter.java

public void setTransactionManager(final PlatformTransactionManager transactionManager) {
    this.transactionManager = transactionManager;
    this.transactionTemplate = new TransactionTemplate(this.transactionManager);
}

From source file:edu.northwestern.bioinformatics.studycalendar.osgi.felixcm.internal.PscFelixPersistenceManager.java

@SuppressWarnings({ "unchecked" })
private void doInitialize(DataSource dataSource, Map dsProperties) throws Exception {
    AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
    sessionFactoryBean.setNamingStrategy(new StudyCalendarNamingStrategy());
    sessionFactoryBean.setDataSource(dataSource);
    sessionFactoryBean.setAnnotatedClasses(new Class[] { OsgiConfigurationProperty.class });

    Properties properties = new Properties();
    // classic translator avoids antlr reflective ugliness
    properties.setProperty("hibernate.query.factory_class",
            "org.hibernate.hql.classic.ClassicQueryTranslatorFactory");
    applyHibernateDialect(dsProperties, properties);
    sessionFactoryBean.setHibernateProperties(properties);

    sessionFactoryBean.afterPropertiesSet();
    setSessionFactory(sessionFactoryBean.getObject());

    transactionManager = new HibernateTransactionManager(getSessionFactory());
    transactionManager.afterPropertiesSet();

    transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.afterPropertiesSet();

    afterPropertiesSet();/*from w  ww .  j a  va  2s.  c om*/
}

From source file:org.ensembl.gti.seqstore.database.JdbcSeqStore.java

public JdbcSeqStore(DataSource dataSource) {
    this.template = new JdbcTemplate(dataSource);
    this.transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
    this.log = LoggerFactory.getLogger(this.getClass());
}

From source file:org.openremote.beehive.configuration.www.SensorsAPI.java

@POST
public Response createSensor(final SensorDTOIn sensorDTO) {
    if (device.getSensorByName(sensorDTO.getName()) != null) {
        return Response.status(Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "A sensor with the same name already exists")).build();
    }//  w  w  w  . j a  v  a 2 s .c o m

    try {
        Command command = device.getCommandById(sensorDTO.getCommandId());
    } catch (NotFoundException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity(new ErrorDTO(400, "Referenced command does not exist")).build();
    }

    return Response.ok(new SensorDTOOut(
            new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Sensor>() {
                @Override
                public Sensor doInTransaction(TransactionStatus transactionStatus) {
                    Sensor newSensor = createSensorFromDTO(sensorDTO);
                    sensorRepository.save(newSensor);
                    return newSensor;
                }
            }))).build();
}

From source file:dao.MetricsDAO.java

public static ObjectNode getPagedMetrics(String dashboardName, String group, Integer page, Integer size,
        String user) {/*  w ww .j a  va  2  s.co  m*/
    Integer userId = UserDAO.getUserIDByUserName(user);

    final JdbcTemplate jdbcTemplate = getJdbcTemplate();
    javax.sql.DataSource ds = jdbcTemplate.getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);

    TransactionTemplate txTemplate = new TransactionTemplate(tm);

    ObjectNode result;
    final Integer id = userId;
    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {
            List<Map<String, Object>> rows;
            if (StringUtils.isBlank(dashboardName)) {
                rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS, id, (page - 1) * size, size);
            } else if (StringUtils.isBlank(group)) {
                String dbName;
                if (dashboardName.equals("[Other]")) {
                    dbName = null;
                } else {
                    dbName = dashboardName;
                }
                rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS_BY_DASHBOARD_NAME, id, dbName, dbName,
                        (page - 1) * size, size);
            } else {
                String dbName;
                if (dashboardName.equals("[Other]")) {
                    dbName = null;
                } else {
                    dbName = dashboardName;
                }
                String grp;
                if (group.equals("[Other]")) {
                    grp = null;
                } else {
                    grp = group;
                }
                rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS_BY_DASHBOARD_AND_GROUP, id, dbName,
                        dbName, grp, grp, (page - 1) * size, size);
            }

            List<Metric> pagedMetrics = new ArrayList<>();
            for (Map row : rows) {
                Metric metric = new Metric();
                metric.id = (int) row.get("metric_id");
                metric.name = (String) row.get("metric_name");
                metric.description = (String) row.get("metric_description");
                metric.refID = (String) row.get("metric_ref_id");
                metric.refIDType = (String) row.get("metric_ref_id_type");
                metric.dashboardName = (String) row.get("dashboard_name");
                metric.category = (String) row.get("metric_category");
                metric.group = (String) row.get("metric_group");
                metric.watchId = (Long) row.get("watch_id");
                pagedMetrics.add(metric);
            }
            long count = 0;
            try {
                count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }

            ObjectNode resultNode = Json.newObject();
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
            resultNode.set("metrics", Json.toJson(pagedMetrics));

            return resultNode;
        }
    });

    return result;
}

From source file:com.github.fharms.camel.route.CamelEntityManagerTestRouteTest.java

@Before
public void setupDatabaseData() {
    txTemplate = new TransactionTemplate(transactionManager);
    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    alphaDoc = createDog("Skippy", "Terrier");
    txTemplate.execute((TransactionCallback) status -> {
        em.persist(alphaDoc);/*from   www . ja va  2 s .  c  om*/
        return null;
    });
}

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);
}