Java Code Examples for org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection()

The following examples show how to use org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSequenceMaxValueIncrementer.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * 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 2
Source File: DatabasePopulatorUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 3
Source File: JdbcTemplate.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@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 4
Source File: JdbcTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 5
Source File: DataSourceAclTablesPopulator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void populate() {
  // resources based on PostgreSQL ACL schema in Spring ACL artifact JAR
  List<String> resourceNames = new ArrayList<>(4);
  resourceNames.add("/sql/create_table_acl_sid.sql");
  resourceNames.add("/sql/create_table_acl_class.sql");
  resourceNames.add("/sql/create_table_acl_object_identity.sql");
  resourceNames.add("/sql/create_table_acl_entry.sql");

  Connection connection = DataSourceUtils.getConnection(dataSource);
  try {
    resourceNames.forEach(resourceName -> createTable(connection, resourceName));
  } finally {
    DataSourceUtils.releaseConnection(connection, dataSource);
  }
}
 
Example 6
Source File: JdbcTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 7
Source File: JdbcTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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());
	}
}
 
Example 8
Source File: AbstractIdentityColumnMaxValueIncrementer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that @@identity
		* returns the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate(getIncrementStatement());
				ResultSet rs = stmt.executeQuery(getIdentityStatement());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("Identity statement failed after inserting");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			stmt.executeUpdate(getDeleteStatement(this.valueCache));
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 9
Source File: JdbcTemplate.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: JdbcTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: MultiDataSourceTransaction.java    From Milkomeda with MIT License 5 votes vote down vote up
@Override
public void close() throws SQLException {
    DataSourceUtils.releaseConnection(this.mainConnection, this.dataSource);
    for (Connection connection : otherConnectionMap.values()) {
        DataSourceUtils.releaseConnection(connection, this.dataSource);
    }
}
 
Example 12
Source File: DBConnection.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public void closeAndRockBack() throws SQLException{
	if (connection != null && connection.isClosed()==false){
		if(connection.getAutoCommit()==false){
			connection.rollback();
		}
		DataSourceUtils.releaseConnection(connection, dataSource);
	}
}
 
Example 13
Source File: LocalDataSourceJobStore.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected void closeConnection(Connection con) {
	// Will work for transactional and non-transactional connections.
	DataSourceUtils.releaseConnection(con, this.dataSource);
}
 
Example 14
Source File: DefaultReportService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
@Transactional(readOnly = true)
public JasperPrint renderReport( OutputStream out, String reportUid, Period period,
    String organisationUnitUid, String type )
{
    I18nFormat format = i18nManager.getI18nFormat();

    Report report = getReport( reportUid );

    Map<String, Object> params = new HashMap<>();

    params.putAll( constantService.getConstantParameterMap() );

    Date reportDate = new Date();

    if ( period != null )
    {
        params.put( PARAM_PERIOD_NAME, format.formatPeriod( period ) );

        reportDate = period.getStartDate();
    }

    OrganisationUnit orgUnit = organisationUnitService.getOrganisationUnit( organisationUnitUid );

    if ( orgUnit != null )
    {
        int level = orgUnit.getLevel();

        params.put( PARAM_ORGANISATIONUNIT_COLUMN_NAME, orgUnit.getName() );
        params.put( PARAM_ORGANISATIONUNIT_LEVEL, level );
        params.put( PARAM_ORGANISATIONUNIT_LEVEL_COLUMN, ORGUNIT_LEVEL_COLUMN_PREFIX + level );
        params.put( PARAM_ORGANISATIONUNIT_UID_LEVEL_COLUMN, ORGUNIT_UID_LEVEL_COLUMN_PREFIX + level );
    }

    JasperPrint print;

    log.debug( String.format( "Get report for report date: '%s', org unit: '%s'", DateUtils.getMediumDateString( reportDate ), organisationUnitUid ) );

    try
    {
        JasperReport jasperReport = JasperCompileManager.compileReport( IOUtils.toInputStream( report.getDesignContent(), StandardCharsets.UTF_8 ) );

        if ( report.hasVisualization() ) // Use JR data source
        {
            Visualization visualization = report.getVisualization();

            Grid grid = visualizationService.getVisualizationGrid( visualization.getUid(), reportDate, organisationUnitUid );

            print = JasperFillManager.fillReport( jasperReport, params, grid );
        }
        else // Use JDBC data source
        {
            if ( report.hasRelativePeriods() )
            {
                AnalyticsFinancialYearStartKey financialYearStart = (AnalyticsFinancialYearStartKey) systemSettingManager.getSystemSetting( SettingKey.ANALYTICS_FINANCIAL_YEAR_START );

                List<Period> relativePeriods = report.getRelatives().getRelativePeriods( reportDate, null, false, financialYearStart );

                String periodString = getCommaDelimitedString( getIdentifiers( periodService.reloadPeriods( relativePeriods ) ) );
                String isoPeriodString = getCommaDelimitedString( IdentifiableObjectUtils.getUids( relativePeriods ) );

                params.put( PARAM_RELATIVE_PERIODS, periodString );
                params.put( PARAM_RELATIVE_ISO_PERIODS, isoPeriodString );
            }

            if ( report.hasReportParams() && report.getReportParams().isOrganisationUnit() && orgUnit != null )
            {
                params.put( PARAM_ORG_UNITS, String.valueOf( orgUnit.getId() ) );
                params.put( PARAM_ORG_UNITS_UID, String.valueOf( orgUnit.getUid() ) );
            }

            Connection connection = DataSourceUtils.getConnection( dataSource );

            try
            {
                print = JasperFillManager.fillReport( jasperReport, params, connection );
            }
            finally
            {
                DataSourceUtils.releaseConnection( connection, dataSource );
            }
        }

        if ( print != null )
        {
            JRExportUtils.export( type, out, print );
        }
    }
    catch ( Exception ex )
    {
        throw new RuntimeException( "Failed to render report", ex );
    }

    return print;
}
 
Example 15
Source File: DynamicSpringManagedTransaction.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Override
public void close() throws SQLException {
    DataSourceUtils.releaseConnection(connection, dataSource);
}
 
Example 16
Source File: LocalDataSourceJobStore.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected void closeConnection(Connection con) {
	// Will work for transactional and non-transactional connections.
	DataSourceUtils.releaseConnection(con, this.dataSource);
}
 
Example 17
Source File: DataSourceTransactionManagerHandler.java    From opensharding-spi-impl with Apache License 2.0 4 votes vote down vote up
@Override
public void unbindResource() {
    ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.unbindResource(transactionManager.getDataSource());
    DataSourceUtils.releaseConnection(holder.getConnection(), transactionManager.getDataSource());
}
 
Example 18
Source File: DerbyMaxValueIncrementer.java    From effectivejava with Apache License 2.0 4 votes vote down vote up
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that last_insert_id()
		* returned the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate("insert into " + getIncrementerName() + " (" + getDummyName() + ") values(null)");
				ResultSet rs = stmt.executeQuery("select IDENTITY_VAL_LOCAL() from " + getIncrementerName());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("IDENTITY_VAL_LOCAL() failed after executing an update");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			long maxValue = this.valueCache[(this.valueCache.length - 1)];
			stmt.executeUpdate("delete from " + getIncrementerName() + " where " + getColumnName() + " < " + maxValue);
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not obtain IDENTITY value", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 19
Source File: MySQLMaxValueIncrementer.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.maxId == this.nextId) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that last_insert_id()
		* returned the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			// Increment the sequence column...
			String columnName = getColumnName();
			stmt.executeUpdate("update "+ getIncrementerName() + " set " + columnName +
					" = last_insert_id(" + columnName + " + " + getCacheSize() + ")");
			// Retrieve the new max of the sequence column...
			ResultSet rs = stmt.executeQuery(VALUE_SQL);
			try {
				if (!rs.next()) {
					throw new DataAccessResourceFailureException("last_insert_id() failed after executing an update");
				}
				this.maxId = rs.getLong(1);
			}
			finally {
				JdbcUtils.closeResultSet(rs);
			}
			this.nextId = this.maxId - getCacheSize() + 1;
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not obtain last_insert_id()", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	else {
		this.nextId++;
	}
	return this.nextId;
}
 
Example 20
Source File: JooqPersistenceModule.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Override
public void release(Connection connection) throws DataAccessException {
  DataSourceUtils.releaseConnection(connection, dataSource);
}