Java Code Examples for org.springframework.jdbc.datasource.DataSourceUtils
The following are top voted examples for showing how to use
org.springframework.jdbc.datasource.DataSourceUtils. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to generate
more good examples.
Example 1
Project: EasyTransaction File: DefaultTransStatusLoggerImpl.java View source code | 6 votes |
@Override public void writeExecuteFlag(String appId, String busCode, String trxId, String pAppId, String pBusCode, String pTrxId, int status) { Connection connection = DataSourceUtils.getConnection(selctor.selectDataSource(appId, busCode, trxId)); try { PreparedStatement prepareStatement = connection.prepareStatement("INSERT INTO `executed_trans` (`app_id`, `bus_code`, `trx_id`,`p_app_id`, `p_bus_code`, `p_trx_id`,`status`) VALUES ( ?, ?, ?, ?, ?, ?, ?);"); prepareStatement.setString(1, appId); prepareStatement.setString(2, busCode); prepareStatement.setString(3, trxId); prepareStatement.setString(4, pAppId); prepareStatement.setString(5, pBusCode); prepareStatement.setString(6, pTrxId); prepareStatement.setInt(7, status); int executeUpdate = prepareStatement.executeUpdate(); if(executeUpdate != 1){ throw new RuntimeException(String.format("insert count(%s) Error!%s %s %s %s %s %s %s", executeUpdate,appId,busCode,trxId,pAppId,pBusCode,pTrxId,status)); } } catch (SQLException e) { throw new RuntimeException("insert Sql failed,check whether the same transaction has been executed?",e); } }
Example 2
Project: EasyTransaction File: DefaultTransStatusLoggerImpl.java View source code | 6 votes |
@Override public void updateExecuteFlagForSlaveTrx(TransactionId pId, EasyTransRequest<?, ?> request, int status) { BusinessIdentifer businessIdentifer = request.getClass().getAnnotation(BusinessIdentifer.class); Connection connection = DataSourceUtils.getConnection(selctor.selectDataSource(businessIdentifer.appId(),businessIdentifer.busCode(),request)); try { PreparedStatement prepareStatement = connection.prepareStatement("UPDATE `executed_trans` SET `status` = ? WHERE `p_app_id` = ? AND `p_bus_code` = ? AND `p_trx_id` = ?;"); prepareStatement.setInt(1, status); prepareStatement.setString(2, pId.getAppId()); prepareStatement.setString(3, pId.getBusCode()); prepareStatement.setString(4, pId.getTrxId()); prepareStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException("updateExecuteFlagForSlaveTrx failed ",e); } }
Example 3
Project: DynamicDataSource File: DynamicMysqlDataSource.java View source code | 6 votes |
/** * 自动上线可用数据源<br/> * 检查AbnormalSlaves,如果正常则丢回normalSlaves */ protected void checkAbnormalSlaves(){ //循环检查所有的失效从库数据源 for(int i = 0; i < abnormalSlaves.size();i++){ DataSource ds = null; Connection conn = null; try { ds = abnormalSlaves.get(i); //step检测可连接性 String ipAndPort = getMapKey(ds); if(ConnUtil.isReachable(ipAndPort, validationQueryTimeout)){ //step: 数据库直连检测 conn = ds.getConnection(); validateSlaveStatus(conn); online(ds); } break; } catch (Throwable e) { continue; }finally{ if(conn != null && ds != null) DataSourceUtils.releaseConnection(conn, ds); } } }
Example 4
Project: DynamicDataSource File: DynamicMysqlDataSource.java View source code | 6 votes |
/** * 自动下线无效数据源<br/> * 检查snormalSlaves,如果不正常则丢到AbnormalSlave */ protected void checkNormalSlaves(){ //循环检查所有的失效从库数据源 for(int i = 0; i < normalSlaves.size();i++){ DataSource ds = null; Connection conn = null; try { ds = normalSlaves.get(i); //step检测可连接性 String ipAndPort = getMapKey(ds); if(!ConnUtil.isReachable(ipAndPort, validationQueryTimeout)){ throw new Exception("不能连接到"+ipAndPort); } conn = ds.getConnection(); validateSlaveStatus(conn); } catch (Throwable e) { logger.error("数据源检查线程发现不可用的数据源",e); offline(ds,e.getMessage()); break; }finally{ if(conn != null && ds != null) DataSourceUtils.releaseConnection(conn, ds); } } }
Example 5
Project: lams File: DatabasePopulatorUtils.java View source code | 6 votes |
/** * Execute the given {@link DatabasePopulator} against the given {@link DataSource}. * @param populator the {@code DatabasePopulator} to execute * @param dataSource the {@code DataSource} to execute against * @throws DataAccessException if an error occurs, specifically a {@link ScriptException} */ public static void execute(DatabasePopulator populator, DataSource dataSource) throws DataAccessException { Assert.notNull(populator, "DatabasePopulator must be provided"); Assert.notNull(dataSource, "DataSource must be provided"); try { Connection connection = DataSourceUtils.getConnection(dataSource); try { populator.populate(connection); } finally { if (connection != null) { DataSourceUtils.releaseConnection(connection, dataSource); } } } catch (Exception ex) { if (ex instanceof ScriptException) { throw (ScriptException) ex; } throw new UncategorizedScriptException("Failed to execute database script", ex); } }
Example 6
Project: lams File: AbstractSequenceMaxValueIncrementer.java View source code | 6 votes |
/** * Executes the SQL as specified by {@link #getSequenceQuery()}. */ @Override protected long getNextKey() throws DataAccessException { Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null; ResultSet rs = null; try { stmt = con.createStatement(); DataSourceUtils.applyTransactionTimeout(stmt, getDataSource()); rs = stmt.executeQuery(getSequenceQuery()); if (rs.next()) { return rs.getLong(1); } else { throw new DataAccessResourceFailureException("Sequence query did not return a result"); } } catch (SQLException ex) { throw new DataAccessResourceFailureException("Could not obtain sequence value", ex); } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
Example 7
Project: lams File: NativeJdbcExtractorAdapter.java View source code | 6 votes |
/** * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection. * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy * and LazyConnectionDataSourceProxy. The target connection behind it is * typically one from a local connection pool, to be unwrapped by the * doGetNativeConnection implementation of a concrete subclass. * @see #doGetNativeConnection * @see org.springframework.jdbc.datasource.ConnectionProxy * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy */ @Override public Connection getNativeConnection(Connection con) throws SQLException { if (con == null) { return null; } Connection targetCon = DataSourceUtils.getTargetConnection(con); Connection nativeCon = doGetNativeConnection(targetCon); if (nativeCon == targetCon) { // We haven't received a different Connection, so we'll assume that there's // some additional proxying going on. Let's check whether we get something // different back from the DatabaseMetaData.getConnection() call. DatabaseMetaData metaData = targetCon.getMetaData(); // The following check is only really there for mock Connections // which might not carry a DatabaseMetaData instance. if (metaData != null) { Connection metaCon = metaData.getConnection(); if (metaCon != null && metaCon != targetCon) { // We've received a different Connection there: // Let's retry the native extraction process with it. nativeCon = doGetNativeConnection(metaCon); } } } return nativeCon; }
Example 8
Project: bdf2 File: DbCommonServiceImpl.java View source code | 6 votes |
public List<String> findDefaultColumnType(String dbInfoId) throws Exception { DataSource ds = this.getDataSourceByDbInfoId(dbInfoId); Connection conn = null; ResultSet resultSet = null; try { conn = DataSourceUtils.getConnection(ds); DatabaseMetaData metaData = conn.getMetaData(); resultSet = metaData.getTypeInfo(); List<String> list = new ArrayList<String>(); while (resultSet.next()) { String typeName = resultSet.getString("TYPE_NAME").toUpperCase(); list.add(typeName); } return list; } finally { JdbcUtils.closeResultSet(resultSet); JdbcUtils.closeConnection(conn); } }
Example 9
Project: bdf2 File: EntityPR.java View source code | 6 votes |
private List<String> loadTablePrimaryKeys(String tableName)throws Exception{ DataSource ds=this.getJdbcTemplate().getDataSource(); Connection con = DataSourceUtils.getConnection(ds); List<String> primaryKeyList=new ArrayList<String>(); Statement stmt = null; ResultSet rs=null; try{ DatabaseMetaData metaData = con.getMetaData(); rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase()); while (rs.next()) { primaryKeyList.add(rs.getString("COLUMN_NAME")); } }finally{ JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(stmt); JdbcUtils.closeConnection(con); } return primaryKeyList; }
Example 10
Project: lodsve-framework File: MyBatisUtils.java View source code | 6 votes |
public static int queryForInt(DataSource dataSource, String sql, Object... params) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; try { ps = DataSourceUtils.doGetConnection(dataSource).prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i + 1, params[i]); } rs = ps.executeQuery(); if (rs.next()) { return rs.getInt(1); } else { return -1; } } finally { if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } } }
Example 11
Project: lodsve-framework File: AbstractDialect.java View source code | 6 votes |
@Override public boolean existTable(String tableName, DataSource dataSource) throws Exception { Assert.notNull(dataSource); Assert.hasText(tableName); String name = dataSource.getConnection().getCatalog(); PreparedStatement ps = null; ResultSet resultSet = null; try { ps = DataSourceUtils.doGetConnection(dataSource).prepareStatement(existTableSql(name, tableName)); resultSet = ps.executeQuery(); return resultSet.next() && resultSet.getInt("count") > 0; } finally { if (ps != null) { ps.close(); } if (resultSet != null) { resultSet.close(); } } }
Example 12
Project: hsweb-framework File: DynamicSpringManagedTransaction.java View source code | 6 votes |
@Override public Connection getConnection() throws SQLException { TransactionProxy proxy = getProxy(); if (proxy != null) { return proxy.getConnection(); } //根据当前激活的数据源 获取jdbc链接 DataSource dataSource = DataSourceHolder.currentDataSource().getNative(); String dsId = switcher().currentDataSourceId(); Connection connection = DataSourceUtils.getConnection(dataSource); proxy = new TransactionProxy(dsId, connection, dataSource); addProxy(proxy); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "DataSource (" + (dsId == null ? "default" : dsId) + ") JDBC Connection [" + connection + "] will" + (proxy.isConnectionTransactional ? " " : " not ") + "be managed by Spring"); } return connection; }
Example 13
Project: spring4-understanding File: DatabasePopulatorUtils.java View source code | 6 votes |
/** * Execute the given {@link DatabasePopulator} against the given {@link DataSource}. * @param populator the {@code DatabasePopulator} to execute * @param dataSource the {@code DataSource} to execute against * @throws DataAccessException if an error occurs, specifically a {@link ScriptException} */ public static void execute(DatabasePopulator populator, DataSource dataSource) throws DataAccessException { Assert.notNull(populator, "DatabasePopulator must be provided"); Assert.notNull(dataSource, "DataSource must be provided"); try { Connection connection = DataSourceUtils.getConnection(dataSource); try { populator.populate(connection); } finally { if (connection != null) { DataSourceUtils.releaseConnection(connection, dataSource); } } } catch (Exception ex) { if (ex instanceof ScriptException) { throw (ScriptException) ex; } throw new UncategorizedScriptException("Failed to execute database script", ex); } }
Example 14
Project: spring4-understanding File: AbstractSequenceMaxValueIncrementer.java View source code | 6 votes |
/** * Executes the SQL as specified by {@link #getSequenceQuery()}. */ @Override protected long getNextKey() throws DataAccessException { Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null; ResultSet rs = null; try { stmt = con.createStatement(); DataSourceUtils.applyTransactionTimeout(stmt, getDataSource()); rs = stmt.executeQuery(getSequenceQuery()); if (rs.next()) { return rs.getLong(1); } else { throw new DataAccessResourceFailureException("Sequence query did not return a result"); } } catch (SQLException ex) { throw new DataAccessResourceFailureException("Could not obtain sequence value", ex); } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
Example 15
Project: spring4-understanding File: NativeJdbcExtractorAdapter.java View source code | 6 votes |
/** * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection. * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy * and LazyConnectionDataSourceProxy. The target connection behind it is * typically one from a local connection pool, to be unwrapped by the * doGetNativeConnection implementation of a concrete subclass. * @see #doGetNativeConnection * @see org.springframework.jdbc.datasource.ConnectionProxy * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy */ @Override public Connection getNativeConnection(Connection con) throws SQLException { if (con == null) { return null; } Connection targetCon = DataSourceUtils.getTargetConnection(con); Connection nativeCon = doGetNativeConnection(targetCon); if (nativeCon == targetCon) { // We haven't received a different Connection, so we'll assume that there's // some additional proxying going on. Let's check whether we get something // different back from the DatabaseMetaData.getConnection() call. DatabaseMetaData metaData = targetCon.getMetaData(); // The following check is only really there for mock Connections // which might not carry a DatabaseMetaData instance. if (metaData != null) { Connection metaCon = metaData.getConnection(); if (metaCon != null && metaCon != targetCon) { // We've received a different Connection there: // Let's retry the native extraction process with it. nativeCon = doGetNativeConnection(metaCon); } } } return nativeCon; }
Example 16
Project: bamboobsc File: HibernateExtendedJpaDialect.java View source code | 6 votes |
@Override public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = (Session) entityManager.getDelegate(); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { getSession(entityManager).getTransaction().setTimeout(definition.getTimeout()); } entityManager.getTransaction().begin(); logger.debug("Transaction started"); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { logger.debug("The connection instance is " + connection.toString()); logger.debug("The isolation level of the connection is " + connection.getTransactionIsolation() + " and the isolation level set on the transaction is " + definition.getIsolationLevel() ); DataSourceUtils.prepareConnectionForTransaction(connection, definition); } }); return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); }
Example 17
Project: blog-java2 File: SpringTestBase.java View source code | 6 votes |
protected void executeSql(String path) { logger.info("executeSql : " + path); Resource resource = new ClassPathResource(path, getClass()); ResourceDatabasePopulator rdp = new ResourceDatabasePopulator(); rdp.addScript(resource); rdp.setSqlScriptEncoding("UTF-8"); rdp.setIgnoreFailedDrops(true); rdp.setContinueOnError(false); try (Connection conn = DataSourceUtils.getConnection(dataSource)) { rdp.populate(conn); } catch (Exception e) { throw new IllegalStateException("executeSql failed, path=" + path, e); } }
Example 18
Project: ignite File: CacheSpringStoreSessionListenerSelfTest.java View source code | 6 votes |
/** */ private void checkConnection() { Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource()); assertNotNull(conn); try { assertFalse(conn.isClosed()); assertEquals(!ses.isWithinTransaction(), conn.getAutoCommit()); } catch (SQLException e) { throw new RuntimeException(e); } verifySameInstance(conn); }
Example 19
Project: welshare File: HibernateExtendedJpaDialect.java View source code | 6 votes |
@Override public Object beginTransaction(EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { DataSourceUtils.prepareConnectionForTransaction(connection, definition); if (connection.isReadOnly() && !definition.isReadOnly()) { connection.setReadOnly(false); } } }); entityManager.getTransaction().begin(); return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); }
Example 20
Project: kansalaisaloite File: JdbcConfiguration.java View source code | 6 votes |
@Bean public PostgresQueryFactory queryFactory() { final DataSource dataSource = dataSource(); return new PostgresQueryFactory(querydslConfiguration(), new Provider<Connection>() { @Override public Connection get() { Connection conn = DataSourceUtils.getConnection(dataSource); if (!DataSourceUtils.isConnectionTransactional(conn, dataSource)) { throw new RuntimeException("Connection is not transactional"); } return conn; } }); }
Example 21
Project: class-guard File: DatabasePopulatorUtils.java View source code | 6 votes |
/** * Execute the given DatabasePopulator against the given DataSource. * @param populator the DatabasePopulator to execute * @param dataSource the DataSource to execute against */ public static void execute(DatabasePopulator populator, DataSource dataSource) { Assert.notNull(populator, "DatabasePopulator must be provided"); Assert.notNull(dataSource, "DataSource must be provided"); try { Connection connection = DataSourceUtils.getConnection(dataSource); try { populator.populate(connection); } finally { if (connection != null) { DataSourceUtils.releaseConnection(connection, dataSource); } } } catch (Exception ex) { throw new DataAccessResourceFailureException("Failed to execute database script", ex); } }
Example 22
Project: class-guard File: AbstractSequenceMaxValueIncrementer.java View source code | 6 votes |
/** * Executes the SQL as specified by {@link #getSequenceQuery()}. */ @Override protected long getNextKey() throws DataAccessException { Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null; ResultSet rs = null; try { stmt = con.createStatement(); DataSourceUtils.applyTransactionTimeout(stmt, getDataSource()); rs = stmt.executeQuery(getSequenceQuery()); if (rs.next()) { return rs.getLong(1); } else { throw new DataAccessResourceFailureException("Sequence query did not return a result"); } } catch (SQLException ex) { throw new DataAccessResourceFailureException("Could not obtain sequence value", ex); } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
Example 23
Project: class-guard File: NativeJdbcExtractorAdapter.java View source code | 6 votes |
/** * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection. * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy * and LazyConnectionDataSourceProxy. The target connection behind it is * typically one from a local connection pool, to be unwrapped by the * doGetNativeConnection implementation of a concrete subclass. * @see #doGetNativeConnection * @see org.springframework.jdbc.datasource.ConnectionProxy * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy */ public Connection getNativeConnection(Connection con) throws SQLException { if (con == null) { return null; } Connection targetCon = DataSourceUtils.getTargetConnection(con); Connection nativeCon = doGetNativeConnection(targetCon); if (nativeCon == targetCon) { // We haven't received a different Connection, so we'll assume that there's // some additional proxying going on. Let's check whether we get something // different back from the DatabaseMetaData.getConnection() call. DatabaseMetaData metaData = targetCon.getMetaData(); // The following check is only really there for mock Connections // which might not carry a DatabaseMetaData instance. if (metaData != null) { Connection metaCon = metaData.getConnection(); if (metaCon != null && metaCon != targetCon) { // We've received a different Connection there: // Let's retry the native extraction process with it. nativeCon = doGetNativeConnection(metaCon); } } } return nativeCon; }
Example 24
Project: syncope File: ProvisioningImpl.java View source code | 6 votes |
@Override public String delete(final String accountid) throws ProvisioningException { LOG.debug("Delete request received"); Connection conn = null; try { conn = DataSourceUtils.getConnection(dataSource); try (PreparedStatement statement = conn.prepareStatement("DELETE FROM user WHERE userId=?")) { statement.setString(1, accountid); String query = "DELETE FROM user WHERE userId='" + accountid + "';"; LOG.debug("Execute query: " + query); statement.executeUpdate(); } return accountid; } catch (SQLException e) { throw new ProvisioningException("Delete operation failed", e); } finally { DataSourceUtils.releaseConnection(conn, dataSource); } }
Example 25
Project: syncope File: JobManagerImpl.java View source code | 6 votes |
private boolean isRunningElsewhere(final JobKey jobKey) throws SchedulerException { if (!scheduler.getScheduler().getMetaData().isJobStoreClustered()) { return false; } DataSource dataSource = domainsHolder.getDomains().get(SyncopeConstants.MASTER_DOMAIN); Connection conn = DataSourceUtils.getConnection(dataSource); PreparedStatement stmt = null; ResultSet resultSet = null; try { stmt = conn.prepareStatement( "SELECT 1 FROM " + Constants.DEFAULT_TABLE_PREFIX + "FIRED_TRIGGERS " + "WHERE JOB_NAME = ? AND JOB_GROUP = ?"); stmt.setString(1, jobKey.getName()); stmt.setString(2, jobKey.getGroup()); resultSet = stmt.executeQuery(); return resultSet.next(); } catch (SQLException e) { throw new SchedulerException(e); } finally { IOUtil.quietClose(resultSet); IOUtil.quietClose(stmt); DataSourceUtils.releaseConnection(conn, dataSource); } }
Example 26
Project: SpringClips File: PersistenceConfigurarion.java View source code | 6 votes |
@Bean @Lazy(false) public ResourceDatabasePopulator populateDatabase() throws SQLException { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(new ClassPathResource("data.sql")); Connection connection = null; try { connection = DataSourceUtils.getConnection(dataSource()); populator.populate(connection); } finally { if (connection != null) { DataSourceUtils.releaseConnection(connection, dataSource()); } } return populator; }
Example 27
Project: oblatum File: SqlGenerator.java View source code | 6 votes |
public List<Column> getColumns(String tableName) throws SQLException { List<Column> columns = new ArrayList<Column>(); Connection connection = DataSourceUtils.getConnection(dataSource); DatabaseMetaData metaData = connection.getMetaData(); ResultSet columnsResultSet = metaData.getColumns(null, metaData.getUserName(), tableName, "%"); while (columnsResultSet.next()) { Column column = new Column(); column.setColumnName(columnsResultSet.getString("COLUMN_NAME").toLowerCase()); column.setDataType(columnsResultSet.getInt("DATA_TYPE")); column.setTypeName(columnsResultSet.getString("TYPE_NAME")); column.setColumnSize(columnsResultSet.getInt("COLUMN_SIZE")); column.setNullable(columnsResultSet.getInt("NULLABLE")); column.setRemarks(columnsResultSet.getString("REMARKS")); column.setColumnDef(columnsResultSet.getString("COLUMN_DEF")); column.setOrdinalPosition(columnsResultSet.getInt("ORDINAL_POSITION")); column.setIsNullable(columnsResultSet.getString("IS_NULLABLE")); column.setIsAutoincrement(columnsResultSet.getString("IS_AUTOINCREMENT")); columns.add(column); } DataSourceUtils.releaseConnection(connection, dataSource); return columns; }
Example 28
Project: cobarclient File: DefaultConcurrentRequestProcessor.java View source code | 6 votes |
private List<RequestDepository> fetchConnectionsAndDepositForLaterUse( List<ConcurrentRequest> requests) { List<RequestDepository> depos = new ArrayList<RequestDepository>(); for (ConcurrentRequest request : requests) { DataSource dataSource = request.getDataSource(); Connection springCon = null; boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy); try { springCon = (transactionAware ? dataSource.getConnection() : DataSourceUtils .doGetConnection(dataSource)); } catch (SQLException ex) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex); } RequestDepository depo = new RequestDepository(); depo.setOriginalRequest(request); depo.setConnectionToUse(springCon); depo.setTransactionAware(transactionAware); depos.add(depo); } return depos; }
Example 29
Project: bandwidth-on-demand File: HibernateJpaDialectWithTransactionIsolationSupport.java View source code | 6 votes |
@Override public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = (Session) entityManager.getDelegate(); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { getSession(entityManager).getTransaction().setTimeout(definition.getTimeout()); } Connection connection = ((SessionImpl) session).connection(); Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(connection, definition); entityManager.getTransaction().begin(); Object transactionDataFromHibernateJpaDialect = prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); return new IsolationSupportSessionTransactionData(transactionDataFromHibernateJpaDialect, previousIsolationLevel, connection); }
Example 30
Project: CommonDao File: JdbcTxCommonDao.java View source code | 6 votes |
/** * 添加支持jdbc datasource Transaction 支持的QueryRunner处理方式 */ @Override protected QueryRunner getQueryRunner() { return new QueryRunner(dataSource){ /* (non-Javadoc) * @see org.apache.commons.dbutils.AbstractQueryRunner#prepareConnection() */ @Override protected Connection prepareConnection() throws SQLException { return DataSourceUtils.getConnection(this.getDataSource()); } /* (non-Javadoc) * @see org.apache.commons.dbutils.AbstractQueryRunner#close(java.sql.Connection) */ @Override protected void close(Connection conn) throws SQLException { DataSourceUtils.releaseConnection(conn, getDataSource()); } }; }
Example 31
Project: replyit-master-3.2-final File: RateCardBL.java View source code | 6 votes |
/** * Returns a list of column names read from the rate table in the database. * @return column names */ public List<String> getRateTableColumnNames() { DataSource dataSource = jdbcTemplate.getDataSource(); Connection connection = DataSourceUtils.getConnection(dataSource); List<String> columns = Collections.emptyList(); try { columns = JDBCUtils.getAllColumnNames(connection, rateCard.getTableName()); } catch (SQLException e) { throw new SessionInternalError("Could not read columns from rate card table.", e, new String[] { "RateCardWS,rates,rate.card.cannot.read.rating.table" }); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } return columns; }
Example 32
Project: replyit-master-3.2-final File: HSQLDBCacheTest.java View source code | 6 votes |
public void testLoader() throws Exception { assertEquals("rules_table", loader.getTableName()); // count the number of records loaded DataSource dataSource = getDataSource(); Connection connection = DataSourceUtils.getConnection(dataSource); Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("select count(*) as REC_COUNT from " + loader.getTableName()); result.next(); long recordsCount = result.getLong("REC_COUNT"); assertTrue("Loader successfully populated records in the database",recordsCount > 0); assertEquals("Loaded correct number of records", 1769, recordsCount); // cleanup result.close(); statement.close(); DataSourceUtils.releaseConnection(connection, dataSource); }
Example 33
Project: javasec File: RmJdbcTemplate.java View source code | 6 votes |
public Object execute(StatementCallback action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null; try { Connection conToUse = con; if (getNativeJdbcExtractor() != null && getNativeJdbcExtractor().isNativeConnectionNecessaryForNativeStatements()) { conToUse = getNativeJdbcExtractor().getNativeConnection(con); } stmt = conToUse.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); applyStatementSettings(stmt); Statement stmtToUse = stmt; if (getNativeJdbcExtractor() != null) { stmtToUse = getNativeJdbcExtractor().getNativeStatement(stmt); } Object result = action.doInStatement(stmtToUse); handleWarnings(stmt); return result; } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. JdbcUtils.closeStatement(stmt); stmt = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex); } finally { JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
Example 34
Project: java-lib File: RmJdbcTemplate.java View source code | 6 votes |
public Object execute(StatementCallback action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null; try { Connection conToUse = con; if (getNativeJdbcExtractor() != null && getNativeJdbcExtractor().isNativeConnectionNecessaryForNativeStatements()) { conToUse = getNativeJdbcExtractor().getNativeConnection(con); } stmt = conToUse.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); applyStatementSettings(stmt); Statement stmtToUse = stmt; if (getNativeJdbcExtractor() != null) { stmtToUse = getNativeJdbcExtractor().getNativeStatement(stmt); } Object result = action.doInStatement(stmtToUse); handleWarnings(stmt); return result; } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. JdbcUtils.closeStatement(stmt); stmt = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex); } finally { JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
Example 35
Project: jkami File: RunConfing.java View source code | 5 votes |
public Connection getConnection() { if (dataSource == null) { throw new RuntimeException("dataSource is null no bean dataSource please set spring xml "); } try { return DataSourceUtils.getConnection(dataSource); } catch (CannotGetJdbcConnectionException e) { try { return dataSource.getConnection(); } catch (SQLException e1) { throw new JkException(e); } } }
Example 36
Project: jkami File: RunConfing.java View source code | 5 votes |
public void doReleaseConnection(Connection con) { try { if (dataSource != null) { DataSourceUtils.doReleaseConnection(con, dataSource); } else { con.close(); } } catch (SQLException e) { e.printStackTrace(); } }
Example 37
Project: Equella File: JDBCOdaResultSet.java View source code | 5 votes |
@Override public void close() throws OdaException { try { if( resultSet != null ) { resultSet.close(); } if( statement != null ) { statement.close(); } if( connection != null ) { DataSourceUtils.releaseConnection(connection, dataSource); } statement = null; connection = null; dataSource = null; rowData = null; resultSet = null; } catch( SQLException e ) { throw new OdaException(e); } }
Example 38
Project: lams File: JdbcTemplate.java View source code | 5 votes |
@Override public <T> T execute(ConnectionCallback<T> action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(getDataSource()); try { Connection conToUse = con; if (this.nativeJdbcExtractor != null) { // Extract native JDBC Connection, castable to OracleConnection or the like. conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } else { // Create close-suppressing Connection proxy, also preparing returned Statements. conToUse = createConnectionProxy(con); } return action.doInConnection(conToUse); } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw getExceptionTranslator().translate("ConnectionCallback", getSql(action), ex); } finally { DataSourceUtils.releaseConnection(con, getDataSource()); } }
Example 39
Project: lams File: JdbcTemplate.java View source code | 5 votes |
@Override public <T> T execute(StatementCallback<T> action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null; try { Connection conToUse = con; if (this.nativeJdbcExtractor != null && this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) { conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } stmt = conToUse.createStatement(); applyStatementSettings(stmt); Statement stmtToUse = stmt; if (this.nativeJdbcExtractor != null) { stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt); } T result = action.doInStatement(stmtToUse); handleWarnings(stmt); return result; } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. JdbcUtils.closeStatement(stmt); stmt = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex); } finally { JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
Example 40
Project: lams File: JdbcTemplate.java View source code | 5 votes |
/** * Prepare the given JDBC Statement (or PreparedStatement or CallableStatement), * applying statement settings such as fetch size, max rows, and query timeout. * @param stmt the JDBC Statement to prepare * @throws SQLException if thrown by JDBC API * @see #setFetchSize * @see #setMaxRows * @see #setQueryTimeout * @see org.springframework.jdbc.datasource.DataSourceUtils#applyTransactionTimeout */ protected void applyStatementSettings(Statement stmt) throws SQLException { int fetchSize = getFetchSize(); if (fetchSize > 0) { stmt.setFetchSize(fetchSize); } int maxRows = getMaxRows(); if (maxRows > 0) { stmt.setMaxRows(maxRows); } DataSourceUtils.applyTimeout(stmt, getDataSource(), getQueryTimeout()); }