Refine search
if (this.useNewConnection) { con = getDataSource().getConnection(); if (con.getAutoCommit()) { mustRestoreAutoCommit = true; con.setAutoCommit(false); con = DataSourceUtils.getConnection(getDataSource()); stmt = con.createStatement(); if (!this.useNewConnection) { DataSourceUtils.applyTransactionTimeout(stmt, getDataSource()); DataSourceUtils.releaseConnection(con, getDataSource());
DataSourceUtils.doReleaseConnection(this.target, this.targetDataSource); this.closed = true; return null; this.target = DataSourceUtils.doGetConnection(this.targetDataSource); actualTarget = DataSourceUtils.doGetConnection(this.targetDataSource); DataSourceUtils.applyTransactionTimeout((Statement) retVal, this.targetDataSource); DataSourceUtils.doReleaseConnection(actualTarget, this.targetDataSource);
@Override protected void doCleanupAfterCompletion(Object transaction) { DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; // Remove the connection holder from the thread, if exposed. if (txObject.isNewConnectionHolder()) { TransactionSynchronizationManager.unbindResource(obtainDataSource()); } // Reset connection. Connection con = txObject.getConnectionHolder().getConnection(); try { if (txObject.isMustRestoreAutoCommit()) { con.setAutoCommit(true); } DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel()); } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } if (txObject.isNewConnectionHolder()) { if (logger.isDebugEnabled()) { logger.debug("Releasing JDBC Connection [" + con + "] after transaction"); } DataSourceUtils.releaseConnection(con, this.dataSource); } txObject.getConnectionHolder().clear(); }
/** * 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 not be null"); Assert.notNull(dataSource, "DataSource must not be null"); try { Connection connection = DataSourceUtils.getConnection(dataSource); try { populator.populate(connection); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } } catch (Throwable ex) { if (ex instanceof ScriptException) { throw (ScriptException) ex; } throw new UncategorizedScriptException("Failed to execute database script", ex); } }
@Override public Connection getConnection() { DataSource dataSource = DataSourceHolder.currentDataSource().getNative(); Connection connection = DataSourceUtils.getConnection(dataSource); boolean isConnectionTransactional = DataSourceUtils.isConnectionTransactional(connection, dataSource); if (logger.isDebugEnabled()) { logger.debug("DataSource ({}) JDBC Connection [{}] will {}be managed by Spring", getDatasourceId(), connection, (isConnectionTransactional ? "" : "not ")); } return connection; }
protected ExecutionStats executeSequentially(JdbcContext context) { Connection conn = null; Statement statement = null; try { long updateCount = 0; long statementCount = 0; conn = DataSourceUtils.doGetConnection(context.getDataSource()); boolean originalAutoCommitSetting = conn.getAutoCommit(); conn.setAutoCommit(false); statement = conn.createStatement(); List<SqlSupplier> suppliers = context.getSuppliers(); for (SqlSupplier supplier : suppliers) { if (supplier instanceof LocationSupplier) { logger.debug("Location: {}", ((LocationSupplier) supplier).getLocation()); } ExecutionStats stats = excecuteSupplier(statement, context, supplier); updateCount += stats.getUpdateCount(); statementCount += stats.getStatementCount(); conn.commit(); } conn.setAutoCommit(originalAutoCommitSetting); return new ExecutionStats(updateCount, statementCount); } catch (Exception e) { throw new IllegalStateException(e); } finally { JdbcUtils.closeQuietly(context.getDataSource(), conn, statement); } }
when(con.getAutoCommit()).thenReturn(false); when(con.createStatement()).thenReturn(stmt); when(stmt.executeQuery("select baz from bar")).thenReturn(rs); when(rs.next()).thenReturn(false); when(con.createStatement()).thenReturn(stmt); when(stmt.executeQuery("select foo from bar")).thenReturn(rs); when(rs.next()).thenReturn(false); final JdbcTemplate template = new JdbcTemplate(csds); Connection connection = DataSourceUtils.getConnection(csds); csds.startCloseSuppression(connection); tt.execute(new TransactionCallback<Void>() { DataSourceUtils.releaseConnection(connection, csds); template.queryForList("select egg from bar");
@Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional assertEquals(con, DataSourceUtils.getConnection(ds)); TransactionAwareDataSourceProxy dsProxy = new TransactionAwareDataSourceProxy(ds); try { assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); // should be ignored dsProxy.getConnection().close(); } catch (SQLException ex) { throw new UncategorizedSQLException("", "", ex); } } });
/** * 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()); } }
@Override protected void doInTransactionWithoutResult(TransactionStatus status) { try { Thread.sleep(1500); } catch (InterruptedException ex) { } try { Connection con = DataSourceUtils.getConnection(ds); PreparedStatement ps = con.prepareStatement("some SQL statement"); DataSourceUtils.applyTransactionTimeout(ps, ds); } catch (SQLException ex) { throw new DataAccessResourceFailureException("", ex); } } });
con = txObject.getConnectionHolder().getConnection(); Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition); txObject.setPreviousIsolationLevel(previousIsolationLevel); if (con.getAutoCommit()) { txObject.setMustRestoreAutoCommit(true); if (logger.isDebugEnabled()) { logger.debug("Switching JDBC Connection [" + con + "] to manual commit"); con.setAutoCommit(false); TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder()); DataSourceUtils.releaseConnection(con, obtainDataSource()); txObject.setConnectionHolder(null, false);
@Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("Is new transaction", status.isNewTransaction()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); Connection tCon = DataSourceUtils.getConnection(dsToUse); try { if (createStatement) { tCon.createStatement(); } } catch (SQLException ex) { throw new UncategorizedSQLException("", "", ex); } } });
@Override @Nullable public <T> T execute(StatementCallback<T> action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(obtainDataSource()); Statement stmt = null; try { stmt = con.createStatement(); applyStatementSettings(stmt); T result = action.doInStatement(stmt); 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. String sql = getSql(action); JdbcUtils.closeStatement(stmt); stmt = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw translateException("StatementCallback", sql, ex); } finally { JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
@Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("Is new transaction", status.isNewTransaction()); Connection con = DataSourceUtils.getConnection(dsToUse); if (createStatement) { try { con.createStatement(); } catch (SQLException ex) { throw new UncategorizedSQLException("", "", ex); } } throw ex; } });
protected void initializeConnection() { Assert.state(getDataSource() != null, "DataSource must not be null."); try { if (useSharedExtendedConnection) { if (!(getDataSource() instanceof ExtendedConnectionDataSourceProxy)) { throw new InvalidDataAccessApiUsageException( "You must use a ExtendedConnectionDataSourceProxy for the dataSource when " + "useSharedExtendedConnection is set to true."); } this.con = DataSourceUtils.getConnection(dataSource); ((ExtendedConnectionDataSourceProxy)dataSource).startCloseSuppression(this.con); } else { this.con = dataSource.getConnection(); } this.initialConnectionAutoCommit = this.con.getAutoCommit(); if (this.connectionAutoCommit != null && this.con.getAutoCommit() != this.connectionAutoCommit) { this.con.setAutoCommit(this.connectionAutoCommit); } } catch (SQLException se) { close(); throw getExceptionTranslator().translate("Executing query", getSql(), se); } }
@Test public void dataSource() throws Exception { Assert.assertEquals(1, this.jdbcTemplate.update("insert into CustomObject (id, text) values (-1, 'test')")); // Check if the Connection returned by DataSource lets us get the inserted object Connection conn = DataSourceUtils.getConnection(this.dataSource); PreparedStatement stmt = conn.prepareStatement("select count(*) from CustomObject where id=-1"); ResultSet rs = stmt.executeQuery(); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertFalse(rs.next()); stmt.close(); rs.close(); // conn.close(); Must not close Connection }
.doGetConnection(dataSource)); session.setUserConnection(springCon); } catch (SQLException ex) { if (springCon != null) { if (transactionAware) { springCon.close(); } else { DataSourceUtils.doReleaseConnection(springCon, dataSource);
@Override public JdbcMetaData getJdbcMetaData(DataSource dataSource) { Connection conn = null; try { conn = DataSourceUtils.doGetConnection(dataSource); DatabaseMetaData dbmd = conn.getMetaData(); return getJdbcMetaData(dbmd); } catch (Exception e) { throw new IllegalStateException(e); } finally { logger.trace("closing connection"); JdbcUtils.closeQuietly(dataSource, conn); } }
con = DataSourceUtils.getConnection(dataSource); DatabaseMetaData metaData = con.getMetaData(); if (metaData == null) { DataSourceUtils.releaseConnection(con, dataSource);
/** * Close the cursor and database connection. Make call to cleanupOnClose so sub classes can cleanup * any resources they have allocated. */ @Override protected void doClose() throws Exception { initialized = false; JdbcUtils.closeResultSet(this.rs); rs = null; cleanupOnClose(); if(this.con != null) { this.con.setAutoCommit(this.initialConnectionAutoCommit); } if (useSharedExtendedConnection && dataSource instanceof ExtendedConnectionDataSourceProxy) { ((ExtendedConnectionDataSourceProxy)dataSource).stopCloseSuppression(this.con); if (!TransactionSynchronizationManager.isActualTransactionActive()) { DataSourceUtils.releaseConnection(con, dataSource); } } else { JdbcUtils.closeConnection(this.con); } }