Example usage for org.springframework.jdbc.datasource DataSourceTransactionManager DataSourceTransactionManager

List of usage examples for org.springframework.jdbc.datasource DataSourceTransactionManager DataSourceTransactionManager

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceTransactionManager DataSourceTransactionManager.

Prototype

public DataSourceTransactionManager(DataSource dataSource) 

Source Link

Document

Create a new DataSourceTransactionManager instance.

Usage

From source file:no.trank.openpipe.jdbc.store.IdStateHolder.java

/**
 * Creates an id state holder with the given configuration.<br/>
 * A {@link SimpleJdbcTemplate} and {@link DataSourceTransactionManager} is created from the given
 * <tt>dataSource</tt>.<br/>
 * A table matching <tt>desc</tt> is created using SQL's created by <tt>sqlFactory</tt> if one doesn't already
 * exists. If a table matching {@link TableDescription#getTableName() desc.getTableName()} already exists, it is
 * validated against <tt>desc</tt>.
 *
 * @param dataSource the datasource to use.
 * @param sqlFactory the factory to use for creating SQL's.
 * @param desc the description of the table to use.
 *//*from  ww w .  j  a v a 2 s.c  om*/
public IdStateHolder(DataSource dataSource, SQLFactory sqlFactory, TableDescription desc) {
    jdbcTemplate = new SimpleJdbcTemplate(dataSource);
    transactionManager = new DataSourceTransactionManager(dataSource);
    this.sqlFactory = sqlFactory;
    final JdbcOperations op = jdbcTemplate.getJdbcOperations();
    final Schema schema = (Schema) op.execute(new SchemaCallback(sqlFactory));
    Table table = schema.getTable(desc.getTableName());
    final SQLGenerator generator = sqlFactory.newSQLGenerator();
    final StringColumn colId;
    final Column colUpd;
    if (table != null) {
        final Column id = table.getColumn(desc.getIdColumnName());
        colUpd = table.getColumn(desc.getUpdColumnName());
        validateTable(id, colUpd, desc.getIdMaxLength());
        colId = (StringColumn) id;
    } else {
        table = schema.newTable(desc.getTableName());
        colId = (StringColumn) table.newColumn(desc.getIdColumnName(), VARCHAR);
        colUpd = table.newColumn(desc.getUpdColumnName(), TIMESTAMP);
        colId.setNullable(false);
        colId.setLength(desc.getIdMaxLength());
        table.newPrimaryKey().addColumn(colId);
        colUpd.setNullable(false);
        createTable(op, table, generator);
    }
    createSqls(table, generator, colId, colUpd);
}

From source file:com.alibaba.otter.node.etl.common.db.dialect.AbstractDbDialect.java

public AbstractDbDialect(JdbcTemplate jdbcTemplate, LobHandler lobHandler, String name, int majorVersion,
        int minorVersion) {
    this.jdbcTemplate = jdbcTemplate;
    this.lobHandler = lobHandler;
    // ?transction
    this.transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    this.databaseName = name;
    this.databaseMajorVersion = majorVersion;
    this.databaseMinorVersion = minorVersion;

    initTables(jdbcTemplate);// www . java 2s  .c  o  m
}

From source file:dao.MetricsDAO.java

public static ObjectNode getPagedMetrics(String dashboardName, String group, Integer page, Integer size,
        String user) {/*  ww w  .j a v  a2  s .  c o 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.joshlong.examples.data.counter.CounterConfiguration.java

@Bean
public PlatformTransactionManager dataSourceTransactionManager() {
    return new DataSourceTransactionManager(this.dataSource());
}

From source file:moviemanager.backend.SpringConfig.java

@Bean // needed for @EnableTransactionManagement
public PlatformTransactionManager transactionManager() {
    return new DataSourceTransactionManager(dataSource());
}

From source file:com.alibaba.otter.node.etl.load.loader.db.interceptor.operation.AbstractOperationInterceptor.java

private void init(final JdbcTemplate jdbcTemplate, final String markTableName, final String markTableColumn) {
    int count = jdbcTemplate
            .queryForInt(MessageFormat.format(checkDataSql, markTableName, GLOBAL_THREAD_COUNT - 1));
    if (count != GLOBAL_THREAD_COUNT) {
        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: init " + markTableName + "'s data.");
        }// www.  ja  v  a2s  .c om
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate
                .setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);// ??????
        transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {
                jdbcTemplate.execute(MessageFormat.format(deleteDataSql, markTableName));
                String batchSql = MessageFormat.format(updateSql,
                        new Object[] { markTableName, markTableColumn });
                jdbcTemplate.batchUpdate(batchSql, new BatchPreparedStatementSetter() {

                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                        ps.setInt(1, idx);
                        ps.setInt(2, 0);
                        // ps.setNull(3, Types.VARCHAR);
                    }

                    public int getBatchSize() {
                        return GLOBAL_THREAD_COUNT;
                    }
                });
                return null;
            }
        });

        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: Init EROSA Client Data: " + updateSql);
        }
    }

}

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:com.vcredit.lrh.db.mysql.LRHMySQLInitConfiguration.java

@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

From source file:edu.dfci.cccb.mev.web.configuration.PersistenceConfiguration.java

@Bean
public PlatformTransactionManager transactionManager(@Named("mev-datasource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

From source file:org.danann.cernunnos.sql.TransactionTask.java

public void perform(final TaskRequest req, final TaskResponse res) {
    PlatformTransactionManager transactionManager = (PlatformTransactionManager) this.transactionManagerPhrase
            .evaluate(req, res);//from w w w.j a  v a 2  s. c o  m
    if (transactionManager == null) {
        //If no transaction manager was found there MUST be a DataSource
        final DataSource dataSource = (DataSource) this.dataSourcePhrase.evaluate(req, res);

        //Create a local DataSourceTransactionManager
        transactionManager = new DataSourceTransactionManager(dataSource);

        //Register the new tx manager in the response for later use if needed
        final String transactionManagerAttrName = (String) this.attributeNamePhrase.evaluate(req, res);
        res.setAttribute(transactionManagerAttrName, transactionManager);

        if (log.isDebugEnabled()) {
            String msg = "Created PlatformTransactionManager '" + transactionManager + "' for DataSource '"
                    + dataSource + "' and bound in response under attribute name '" + transactionManagerAttrName
                    + "'.";
            this.log.debug(msg);
        }
    } else {
        if (log.isDebugEnabled()) {
            String msg = "Found PlatformTransactionManager '" + transactionManager + "' in request.";
            this.log.debug(msg);
        }
    }

    //Create the tx template
    final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

    //Execute the transaction in a callback
    final TransactionCallback transactionCallback = new PerformSubtasksTransactionCallback(this, req, res);
    transactionTemplate.execute(transactionCallback);
}