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

The following are Jave code examples for showing how to use releaseConnection() of the org.springframework.jdbc.datasource.DataSourceUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: DynamicDataSource   File: DynamicMysqlDataSource.java   View Source Code Vote up 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 2
Project: lams   File: DatabasePopulatorUtils.java   View Source Code Vote up 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 3
Project: lams   File: AbstractSequenceMaxValueIncrementer.java   View Source Code Vote up 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 4
Project: spring4-understanding   File: DatabasePopulatorUtils.java   View Source Code Vote up 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 5
Project: spring4-understanding   File: AbstractSequenceMaxValueIncrementer.java   View Source Code Vote up 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 6
Project: class-guard   File: DatabasePopulatorUtils.java   View Source Code Vote up 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 7
Project: oblatum   File: SqlGenerator.java   View Source Code Vote up 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 8
Project: class-guard   File: AbstractSequenceMaxValueIncrementer.java   View Source Code Vote up 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 9
Project: syncope   File: ProvisioningImpl.java   View Source Code Vote up 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 10
Project: syncope   File: JobManagerImpl.java   View Source Code Vote up 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 11
Project: CommonDao   File: JdbcTxCommonDao.java   View Source Code Vote up 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 12
Project: replyit-master-3.2-final   File: RateCardBL.java   View Source Code Vote up 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 13
Project: replyit-master-3.2-final   File: HSQLDBCacheTest.java   View Source Code Vote up 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 14
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 5 votes
/**
 * 
 * */
public Map<String, Map<String, Object>> query(String sql, String key) {
	try {
		Map<String, Map<String, Object>> resultMap = new KeyMap<Map<String, Object>>();
		Connection conn = DataSourceUtils.getConnection(dataSource);
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			while (rs.next()) {
				Map<String, Object> itemMap = new KeyMap<Object>();
				for (int x = 0; x < rsmd.getColumnCount(); x++) {
					itemMap.put(rsmd.getColumnLabel(x + 1), rs.getObject(x + 1));
				}
				resultMap.put(StringTools.toString(itemMap.get(key)), itemMap);
			}
		} catch (Exception e) {
			MyDogLog.getLog().error(" query ", e);
		} finally {
			JdbcUtils.closeResultSet(rs);
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, dataSource);
		}

		return resultMap;
	} finally {
		DataSourceUtils.releaseConnection(DataSourceUtils.getConnection(dataSource), dataSource);
	}
}
 
Example 15
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 5 votes
/**
 * 
 * */
public Map<String, Map<String, Object>> query(String sql, String key) {
	try {
		Map<String, Map<String, Object>> resultMap = new KeyMap<Map<String, Object>>();
		Connection conn = DataSourceUtils.getConnection(dataSource);
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			while (rs.next()) {
				Map<String, Object> itemMap = new KeyMap<Object>();
				for (int x = 0; x < rsmd.getColumnCount(); x++) {
					itemMap.put(rsmd.getColumnLabel(x + 1), rs.getObject(x + 1));
				}
				resultMap.put(StringTools.toString(itemMap.get(key)), itemMap);
			}
		} catch (Exception e) {
			MyDogLog.getLog().error(" query ", e);
		} finally {
			JdbcUtils.closeResultSet(rs);
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, dataSource);
		}

		return resultMap;
	} finally {
		DataSourceUtils.releaseConnection(DataSourceUtils.getConnection(dataSource), dataSource);
	}
}
 
Example 16
Project: Equella   File: JDBCOdaResultSet.java   View Source Code Vote up 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 17
Project: lams   File: JdbcTemplate.java   View Source Code Vote up 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 18
Project: spwrap   File: ConnectionManager.java   View Source Code Vote up 5 votes
void closeConnection(Connection connection, DataSource dataSource) {
    if (connection != null && dataSource != null) {
        DataSourceUtils.releaseConnection(connection, dataSource);
    } else {
        Util.closeDBObjects(connection, null, null);
    }
}
 
Example 19
Project: OperatieBRP   File: ZoekPersoonRepositoryImpl.java   View Source Code Vote up 5 votes
@Override
public boolean isPostgres() throws SQLException {
    Connection connection = null;
    try {
        connection = DataSourceUtils.getConnection(masterDataSource);
        final String url = connection.getMetaData().getURL();
        return url.contains("postgres");
    } finally {
        DataSourceUtils.releaseConnection(connection, masterDataSource);
    }
}
 
Example 20
Project: hsweb-framework   File: DefaultJdbcExecutor.java   View Source Code Vote up 5 votes
@Override
public void releaseConnection(Connection connection) throws SQLException {
    if (logger.isDebugEnabled()) {
        logger.debug("Releasing DataSource ({}) JDBC Connection [{}]", getDatasourceId(), connection);
    }
    DataSourceUtils.releaseConnection(connection, DataSourceHolder.currentDataSource().getNative());
}
 
Example 21
Project: spring4-understanding   File: AbstractIdentityColumnMaxValueIncrementer.java   View Source Code Vote up 5 votes
@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 22
Project: spring4-understanding   File: JdbcTemplate.java   View Source Code Vote up 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 23
Project: spring4-understanding   File: JdbcTemplate.java   View Source Code Vote up 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 24
Project: unitils   File: DbUnitDatabaseConnection.java   View Source Code Vote up 5 votes
/**
 * Closes the <code>Connection</code> that was last retrieved using the {@link #getConnection} method
 *
 * @throws SQLException When connection close fails
 */
public void closeJdbcConnection() throws SQLException {
    if (currentlyUsedConnection != null) {
        DataSourceUtils.releaseConnection(currentlyUsedConnection, dataSource);
        currentlyUsedConnection = null;
        currentlyUsedNativeConnection = null;
    }
}
 
Example 25
Project: jdbc   File: PostgresTestSupport.java   View Source Code Vote up 5 votes
@Override
protected void obtainResource() {
	context = new SpringApplicationBuilder(Config.class)
			.web(WebApplicationType.NONE)
			.run();
	DataSource dataSource = context.getBean(DataSource.class);
	Connection con = DataSourceUtils.getConnection(dataSource);
	DataSourceUtils.releaseConnection(con, dataSource);
}
 
Example 26
Project: cernunnos   File: OpenConnectionTask.java   View Source Code Vote up 5 votes
protected void performCreateConnection(TaskRequest req, TaskResponse res, DataSource dataSource) {
    final Connection connection = DataSourceUtils.getConnection(dataSource);
 try {
	    // Make it available as a request attribute...
        final String connectionAttrName = (String) attribute_name.evaluate(req, res);
        res.setAttribute(connectionAttrName, connection);
        
        // Invoke subtasks...
        super.performSubtasks(req, res);
 }
 finally {
     DataSourceUtils.releaseConnection(connection, dataSource);
 }
}
 
Example 27
Project: ldtm   File: LdtmDataSourceTransactionManager.java   View Source Code Vote up 5 votes
@Override
protected void doCleanupAfterCompletion(Object transaction) {
	DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;

	// Remove the connection holder from the thread, if exposed.
	if (txObject.isNewConnectionHolder()) {
		TransactionSynchronizationManager.unbindResource(this.dataSource);
	}

	// 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();
}
 
Example 28
Project: nway-jdbc   File: SqlExecutor.java   View Source Code Vote up 5 votes
private void initPaginationSupport() {

		Connection conn = null;
		
		String databaseProductName = null;

		try {
			
			conn = getDataSource().getConnection();
					
			databaseProductName = conn.getMetaData().getDatabaseProductName().toUpperCase();
		} 
		catch (SQLException e) {
			
			throw new CannotGetJdbcConnectionException("�������ݿ�ʧ��", e);
		}
		finally {
			
			if(conn != null) {
				
				DataSourceUtils.releaseConnection(conn, getDataSource());
			}
		}

		if (databaseProductName.contains("ORACLE")) {
			
			this.paginationSupport = new OraclePaginationSupport();
		} 
		else if (databaseProductName.contains("MYSQL")
				|| databaseProductName.contains("MARIADB")) {
			
			this.paginationSupport = new MysqlPaginationSupport();
		} 
		else {
			
			throw new UnsupportedOperationException("�ݲ�֧�ֱ����ݿ�ķ�ҳ��������ʵ��com.nway.spring.jdbc.PaginationSupport�ӿڣ�ͨ������setPaginationSupport�������롣");
		}
	}
 
Example 29
Project: cambodia   File: SBulletinDao.java   View Source Code Vote up 5 votes
public int doUpdate(SBulletin bul) throws Exception{
		String sql = "update s_bulletin " +
				" set BULLETIN_TITLE = ?, " +
//				" CREATE_DATE = ?, " +
				" BULLETIN_CONTENT= ?, " +
//				" BULLETIN_PUBLISHER= ?, " +
//				" STATUS= ?, " +
//				" OPTR_ID= ?, " +
				" EFF_DATE= ?, " +
				" EXP_DATE= ? " +
				" where bulletin_id = ?";
		Connection conn = this.getConnection();
		PreparedStatement pst = null;
		int result = 0;
		try{
			pst = conn.prepareStatement(sql);
			pst.setString(1, bul.getBulletin_title());//BULLETIN_TITLE
			
			C3P0NativeJdbcExtractor cp30NativeJdbcExtractor = new C3P0NativeJdbcExtractor(); 
			OracleConnection oracleConn = (OracleConnection) cp30NativeJdbcExtractor.getNativeConnection(pst.getConnection());
			CLOB clob = oracle.sql.CLOB.createTemporary(oracleConn, false, oracle.sql.CLOB.DURATION_SESSION);
			clob.putString(1,bul.getBulletin_content());
			pst.setClob(2, clob);//BULLETIN_CONTENT
			pst.setDate(3, new java.sql.Date(bul.getEff_date().getTime()));//EFF_DATE
			pst.setDate(4, new java.sql.Date(bul.getExp_date().getTime()));//EXP_DATE
			pst.setString(5, bul.getBulletin_id());
			result = pst.executeUpdate();
		}catch (SQLException ex) {
			JdbcUtils.closeStatement(pst);
			pst = null;
			DataSourceUtils.releaseConnection(conn, getDataSource());
			conn = null;
			throw ex;
		}finally {
			JdbcUtils.closeStatement(pst);
			DataSourceUtils.releaseConnection(conn, getDataSource());
		}
		return result;
	}
 
Example 30
Project: cambodia   File: SBulletinDao.java   View Source Code Vote up 5 votes
public int doSave(SBulletin bulletin) throws Exception{
	//  SEQ_S_BULLETIN.Nextval,bulletin_content,create_date,bulletin_title,
	// status,exp_date,optr_id,bulletin_publisher,bulletin_id,eff_date
	String sql = "INSERT INTO S_BULLETIN (bulletin_id,bulletin_content,create_date,bulletin_title," +
			"status,exp_date,optr_id,bulletin_publisher,eff_date) " +
			"values (?,?,sysdate,?,?,?,?,?,?)";
	Connection conn = this.getConnection();
	PreparedStatement pst = null;
	int result = 0;
	try{
		pst = conn.prepareStatement(sql);
		C3P0NativeJdbcExtractor cp30NativeJdbcExtractor = new C3P0NativeJdbcExtractor(); 
		OracleConnection oracleConn = (OracleConnection) cp30NativeJdbcExtractor.getNativeConnection(pst.getConnection());
		pst.setString(1, bulletin.getBulletin_id());
		CLOB clob = oracle.sql.CLOB.createTemporary(oracleConn, false, oracle.sql.CLOB.DURATION_SESSION);
		clob.putString(1,bulletin.getBulletin_content());
		pst.setClob(2, clob);//bulletin_content
		pst.setString(3, bulletin.getBulletin_title());//bulletin_title
		pst.setString(4, bulletin.getStatus());//status
		pst.setDate(5, new java.sql.Date(bulletin.getExp_date().getTime()));//exp_date
		pst.setString(6, bulletin.getOptr_id());//optr_id
		pst.setString(7, bulletin.getBulletin_publisher());//bulletin_publisher
		pst.setDate(8, new java.sql.Date(bulletin.getEff_date().getTime()));//eff_date
		result = pst.executeUpdate();
	}catch (SQLException ex) {
		JdbcUtils.closeStatement(pst);
		pst = null;
		DataSourceUtils.releaseConnection(conn, getDataSource());
		conn = null;
		throw ex;
	}finally {
		JdbcUtils.closeStatement(pst);
		DataSourceUtils.releaseConnection(conn, getDataSource());
	}
	return result;
}
 
Example 31
Project: qafe-platform   File: SQLQueryDAO.java   View Source Code Vote up 5 votes
/**
 * @param ds
 * @param tableName
 * @throws SQLException
 */
private void populateTableColumnSet(DataSource ds, String tableName) throws SQLException {
	Connection conn = ds.getConnection();
	DatabaseMetaData dbmd = conn.getMetaData();
	ResultSet rsc = dbmd.getColumns(conn.getCatalog(), null, tableName, "%");
	Set<String> foundColumnSet = new HashSet<String>();
	while (rsc.next()) {
		String columnName = rsc.getString("COLUMN_NAME");
		foundColumnSet.add(columnName);
	}
	tableColumnSet.put(tableName, foundColumnSet);
	DataSourceUtils.releaseConnection(conn, ds);
}
 
Example 32
Project: qafe-platform   File: RDBDatasource.java   View Source Code Vote up 5 votes
public void destroy(ApplicationContext context) {
    if (dataSource != null) {
        try {
            DataSourceUtils.releaseConnection(dataSource.getConnection(), dataSource);
        } catch (SQLException e) {
            LOG.log(Level.WARNING, "Problem releasing db connection", e);
        }
        // if (!dataSource.getConnection().isClosed()){
        // // You call close() on the Connection object when you're done. Note that this doesn't really
        // close the connection - it just returns it to the pool.
        // dataSource.getConnection().close();
        // }
    }
}
 
Example 33
Project: oblatum   File: SqlGenerator.java   View Source Code Vote up 5 votes
public List<String> getPrimaryKeys(String tableName) throws SQLException {
    List<String> primaryKeys = new ArrayList<String>();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    DatabaseMetaData metaData = connection.getMetaData();
    ResultSet primaryKeysResultSet = metaData.getPrimaryKeys(null, metaData.getUserName(), tableName);
    while (primaryKeysResultSet.next()) {
        primaryKeys.add(primaryKeysResultSet.getString("COLUMN_NAME").toLowerCase());
    }
    DataSourceUtils.releaseConnection(connection, dataSource);
    return primaryKeys;
}
 
Example 34
Project: class-guard   File: JdbcTemplate.java   View Source Code Vote up 5 votes
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 35
Project: InSpider   File: GenerateAttributeMappings.java   View Source Code Vote up 5 votes
@Override
public void run () {
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		PreparedStatement stmt = connection.prepareStatement("select pg_try_advisory_lock(?)");
		stmt.setLong(1, ADVISORY_LOCK_KEY);
		ResultSet rs = stmt.executeQuery();
		boolean result = false;
		while(rs.next()) {
			result = rs.getBoolean(1);
			
		}
		
		rs.close();
		stmt.close();
		
		if(!result) {
			System.err.println("Couldn't acquire lock (JobExecutor already running?)");				
			return;
		}
		
		for (final Dataset ds: managerDao.getAllDatasets ()) {
			processDataset (ds);
		}
		
		DataSourceUtils.releaseConnection(connection, dataSource);
	} catch (Exception e) {
		e.printStackTrace ();
	}
}
 
Example 36
Project: InSpider   File: VerifyDatasetSchemas.java   View Source Code Vote up 5 votes
@Override
public void run () {
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		PreparedStatement stmt = connection.prepareStatement("select pg_try_advisory_lock(?)");
		stmt.setLong(1, ADVISORY_LOCK_KEY);
		ResultSet rs = stmt.executeQuery();
		boolean result = false;
		while(rs.next()) {
			result = rs.getBoolean(1);
			
		}
		
		rs.close();
		stmt.close();
		
		if(!result) {
			System.err.println("Couldn't acquire lock (JobExecutor already running?)");				
			return;
		}
		
		System.out.println ("Listing dataset");
		final OutputStream os = new FileOutputStream ("datasets.csv");
		final PrintWriter writer = new PrintWriter (new OutputStreamWriter (os, Charset.forName ("UTF-8")));
		
		for (final Dataset ds: managerDao.getAllDatasets ()) {
			processDataset (ds, writer);
		}
		
		writer.close ();
		os.close ();
		
		DataSourceUtils.releaseConnection(connection, dataSource);
	} catch (Exception e) {
		e.printStackTrace ();
	}
}
 
Example 37
Project: InSpider   File: GeneralizeReader.java   View Source Code Vote up 5 votes
@Transactional(propagation=Propagation.MANDATORY)
public void delete() throws SQLException, IOException {
	Connection connection = DataSourceUtils.getConnection(dataSource);
	
	Statement stmt = connection.createStatement();
	for(GeneralizeJob job : generalizerConfig.getGeneralizeJobs()) {
		String destination = job.getDestination();
		
		logger.debug("" + stmt.executeUpdate("delete from " + destination) + 
			" features deleted from " + destination);
	}
	stmt.close();
	
	DataSourceUtils.releaseConnection(connection, dataSource);
}
 
Example 38
Project: qb-core   File: RmJdbcTemplate.java   View Source Code Vote up 5 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 39
Project: fixflow   File: DBConnection.java   View Source Code Vote up 5 votes
public void close() throws SQLException{
	if (connection != null && connection.isClosed()==false){
		if(connection.getAutoCommit()==false){
			connection.commit();
		}
		DataSourceUtils.releaseConnection(connection, dataSource);
	}
}
 
Example 40
Project: fixflow   File: DBConnection.java   View Source Code Vote up 5 votes
public void closeAndRockBack() throws SQLException{
	if (connection != null && connection.isClosed()==false){
		if(connection.getAutoCommit()==false){
			connection.rollback();
		}
		DataSourceUtils.releaseConnection(connection, dataSource);
	}
}
 
Example 41
Project: copper-engine   File: SpringTransaction.java   View Source Code Vote up 5 votes
public void run(PlatformTransactionManager transactionManager, DataSource dataSource, TransactionDefinition def) throws Exception {
    TransactionStatus txnStatus = transactionManager.getTransaction(def);
    try {
        Connection con = DataSourceUtils.getConnection(dataSource);
        try {
            execute(con);
        } finally {
            DataSourceUtils.releaseConnection(con, dataSource);
        }
    } catch (Exception e) {
        transactionManager.rollback(txnStatus);
        throw e;
    }
    transactionManager.commit(txnStatus);
}
 
Example 42
Project: javasec   File: RmJdbcTemplate.java   View Source Code Vote up 5 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 43
Project: java-lib   File: RmJdbcTemplate.java   View Source Code Vote up 5 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 44
Project: spark-project   File: SpringConfig.java   View Source Code Vote up 4 votes
@Override
public void close(ResultSet rs, Statement st, Connection conn) {
    if (rs != null) JdbcUtils.closeResultSet(rs);
    if (st != null) JdbcUtils.closeStatement(st);
    DataSourceUtils.releaseConnection(conn, getDataSource());
}
 
Example 45
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 4 votes
/**
 * 查询表元数据相关信息
 */
public Map<String, ResultType> queryTableMetas(String tableName) {
	Map<String, ResultType> resultTypes = new KeyMap<ResultType>(); 
	Map<String, Map<String, Object>> columnInfo = query(String.format(SHOW_TABLE_DESC_SQL, tableName), "field");
	Connection connection = DataSourceUtils.getConnection(dataSource);
	PreparedStatement ps = null;
	ResultSet rs = null;
	XmlConfigLoader configLoader = XmlConfigLoader.getConfigLoader();
	TableModel tableModel = configLoader.getTableMap().get(tableName) ;
	try {
		ps = connection.prepareStatement(String.format("select * from %s", tableName));
		rs = ps.executeQuery();
		ResultSetMetaData rsmd = rs.getMetaData();
		int cloumnLength = rsmd.getColumnCount();
		
		for(int x=0;x<cloumnLength;x++){
			ResultType resultType = new ResultType();
			String field = rsmd.getColumnLabel(x+1);
			Map<String, Object> fieldMap = columnInfo.get( field );
			String extra = StringTools.toString(fieldMap.get("extra")) ;
			resultType.setAutoIncrement("auto_increment".equals(extra)) ; 
			resultType.setPri("pri".equalsIgnoreCase(StringTools.toString(fieldMap.get("key")))) ; 
			resultType.setColumnLabel(field) ;
			resultType.setColumnName( rsmd.getColumnName(x+1) ) ;
			ColumnOverride columnOverride = tableModel.getColumnOverride().get( field ) ;
			
			resultType.setColumnType( rsmd.getColumnType(x+1) ) ;
			if(columnOverride == null){
				resultType.setColumnTypeName( resultType.getJdbcType().name() ) ;
				resultType.setClassName(rsmd.getColumnClassName(x+1)) ;
			}else{
				resultType.setColumnTypeName(columnOverride.getJdbcType().name()) ;
				resultType.setClassName( columnOverride.getJavaType() ) ; 
			}
			
			resultType.setProperty( StringTools.toProperty(field) ) ;
			resultType.setComment( StringTools.toString( fieldMap.get("comment"))) ;
			resultType.setGenerateClassName( resultType.getClassName().replaceAll("java.lang.", "")); 
			
			/*修改链接符号*/
			ColumnSymbol columnSymbol = tableModel.getColumnSymbols().get( field ) ;
			if(null != columnSymbol){
				columnSymbol.setQueryValue( columnSymbol.getValue().replaceAll("\\{value\\}", "#{"+resultType.getProperty()+"}")); 
				resultType.setColumnSymbol( columnSymbol );
			}
			 
			/*设置字段显示的值*/
			resultType.setColumnValue( tableModel.getColumnValue().get(field) ) ;
			
			resultTypes.put(field, resultType) ; 
			
		}
	} catch (Exception e) {
		MyDogLog.getLog().error(" queryTableMetas ", e);
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(ps);
		DataSourceUtils.releaseConnection(connection, dataSource);
	}

	return resultTypes;
}
 
Example 46
Project: lams   File: LocalDataSourceJobStore.java   View Source Code Vote up 4 votes
@Override
protected void closeConnection(Connection con) {
	// Will work for transactional and non-transactional connections.
	DataSourceUtils.releaseConnection(con, this.dataSource);
}
 
Example 47
Project: lams   File: SybaseMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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
		* returnes 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("select @@identity");
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("@@identity 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 increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 48
Project: lams   File: SqlServerMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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
		* returnes 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() + " default values");
				ResultSet rs = stmt.executeQuery("select @@identity");
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("@@identity 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 increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 49
Project: lams   File: MySQLMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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 50
Project: lams   File: DerbyMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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 51
Project: lams   File: HsqlMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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() + " values(null)");
				ResultSet rs = stmt.executeQuery("select max(identity()) from " + getIncrementerName());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("identity() 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()", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 52
Project: jTransactions   File: SpringTxConnectionManager.java   View Source Code Vote up 4 votes
@Override
public void releaseConnection(Connection conn, DataSource ds) throws SQLException {
	DataSourceUtils.releaseConnection(conn, ds);
}
 
Example 53
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 4 votes
/**
 * 查询表元数据相关信息
 */
public Map<String, ResultType> queryTableMetas(String tableName) {
	Map<String, ResultType> resultTypes = new HashMap<String, ResultType>();
	Map<String, Map<String, Object>> columnInfo = query(String.format(SHOW_TABLE_DESC_SQL, tableName), "field");
	Connection connection = DataSourceUtils.getConnection(dataSource);
	PreparedStatement ps = null;
	ResultSet rs = null;
	XmlConfigLoader configLoader = XmlConfigLoader.getConfigLoader();
	TableModel tableModel = configLoader.getTableMap().get(tableName) ;
	try {
		ps = connection.prepareStatement(String.format("select * from %s", tableName));
		rs = ps.executeQuery();
		ResultSetMetaData rsmd = rs.getMetaData();
		int cloumnLength = rsmd.getColumnCount();
		
		for(int x=0;x<cloumnLength;x++){
			ResultType resultType = new ResultType();
			String field = rsmd.getColumnLabel(x+1);
			Map<String, Object> fieldMap = columnInfo.get( field );
			String extra = StringTools.toString(fieldMap.get("extra")) ;
			resultType.setAutoIncrement("auto_increment".equals(extra)) ; 
			resultType.setPri("pri".equalsIgnoreCase(StringTools.toString(fieldMap.get("key")))) ; 
			resultType.setColumnLabel(field) ;
			resultType.setColumnName( rsmd.getColumnName(x+1) ) ;
			ColumnOverride columnOverride = tableModel.getColumnOverride().get( field ) ;
			
			resultType.setColumnType( rsmd.getColumnType(x+1) ) ;
			if(columnOverride == null){
				resultType.setColumnTypeName( resultType.getJdbcType().name() ) ;
				resultType.setClassName(rsmd.getColumnClassName(x+1)) ;
			}else{
				resultType.setColumnTypeName(columnOverride.getJdbcType().name()) ;
				resultType.setClassName( columnOverride.getJavaType() ) ; 
			}
			
			resultType.setProperty( StringTools.toProperty(field) ) ;
			resultType.setComment( StringTools.toString( fieldMap.get("comment"))) ;
			resultType.setGenerateClassName( resultType.getClassName().replaceAll("java.lang.", "")); 
			
			/*修改链接符号*/
			ColumnSymbol columnSymbol = tableModel.getColumnSymbols().get( field ) ;
			if(null != columnSymbol){
				columnSymbol.setQueryValue( columnSymbol.getValue().replaceAll("\\{value\\}", "#{"+resultType.getProperty()+"}")); 
				resultType.setColumnSymbol( columnSymbol );
			}
			 
			/*设置字段显示的值*/
			resultType.setColumnValue( tableModel.getColumnValue().get(field) ) ;
			resultTypes.put(field, resultType) ; 
			
		}
	} catch (Exception e) {
		MyDogLog.getLog().error(" queryTableMetas ", e);
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(ps);
		DataSourceUtils.releaseConnection(connection, dataSource);
	}

	return resultTypes;
}
 
Example 54
Project: lodsve-framework   File: MySQLIDGenerator.java   View Source Code Vote up 4 votes
@Override
 public synchronized Long nextId(String sequenceName) {
     if (NEXT_ID_CACHE.get(sequenceName) != null) {
         this.nextId = NEXT_ID_CACHE.get(sequenceName);
     }
     if (MAX_ID_CACHE.get(sequenceName) != null) {
         this.maxId = MAX_ID_CACHE.get(sequenceName);
     }

     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(dataSource);
         Statement stmt = null;
         try {
             stmt = con.createStatement();
             DataSourceUtils.applyTransactionTimeout(stmt, dataSource);
             String updateSql = "update " + sequenceName + " set " + sequenceName + " = last_insert_id(" + sequenceName + " + " + getCacheSize() + ")";
             try {
                 // Increment the sequence column...
                 stmt.executeUpdate(updateSql);
             } catch (SQLException e) {
                 //发生异常,即不存在这张表
                 //1.执行新建这张表的语句
                 StringBuffer createSql = new StringBuffer();
                 createSql.append("create table ").append(sequenceName).append(" ( ");
                 createSql.append(sequenceName).append(" bigint(12) default null ");
                 createSql.append(" ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ");
                 stmt.execute(createSql.toString());
                 //2.初始化这张表的数据(将name的值置为0)
                 String initDataSql = "insert into " + sequenceName + " values(0)";
                 stmt.executeUpdate(initDataSql);
                 //3.Increment the sequence column...
                 stmt.executeUpdate(updateSql);
             }
             // 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);
                 //更新缓存
                 MAX_ID_CACHE.put(sequenceName, this.maxId);
             } finally {
                 JdbcUtils.closeResultSet(rs);
             }
             this.nextId = this.maxId - getCacheSize() + 1;
             //更新缓存
             NEXT_ID_CACHE.put(sequenceName, this.nextId);
         } catch (SQLException ex) {
             throw new DataAccessResourceFailureException("Could not obtain last_insert_id()", ex);
         } finally {
             JdbcUtils.closeStatement(stmt);
             DataSourceUtils.releaseConnection(con, dataSource);
         }
     } else {
         this.nextId++;
         //更新缓存
         NEXT_ID_CACHE.put(sequenceName, this.nextId);
     }
     long result = this.nextId;

     //初始化nextId和maxId
     this.nextId = 0;
     this.maxId = 0;
     return result;
 }
 
Example 55
Project: hsweb-framework   File: DynamicSpringManagedTransaction.java   View Source Code Vote up 4 votes
@Override
public void close() throws SQLException {
    DataSourceUtils.releaseConnection(connection, dataSource);
}
 
Example 56
Project: spring4-understanding   File: MySQLMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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 57
Project: spring4-understanding   File: LocalDataSourceJobStore.java   View Source Code Vote up 4 votes
@Override
protected void closeConnection(Connection con) {
	// Will work for transactional and non-transactional connections.
	DataSourceUtils.releaseConnection(con, this.dataSource);
}
 
Example 58
Project: tcc-transaction   File: SpringJdbcTransactionRepository.java   View Source Code Vote up 4 votes
protected void releaseConnection(Connection con) {
    DataSourceUtils.releaseConnection(con, this.getDataSource());
}
 
Example 59
Project: treeleaf   File: SpringDBConnectionFactory.java   View Source Code Vote up 4 votes
public void releaseConnection(Connection connection) {
    DataSourceUtils.releaseConnection(connection, this.dataSource);
}
 
Example 60
Project: mybatis-spring-1.2.2   File: SpringManagedTransaction.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
public void close() throws SQLException {
  DataSourceUtils.releaseConnection(this.connection, this.dataSource);
}
 
Example 61
Project: spring-jdbctemplate-streams   File: JdbcStream.java   View Source Code Vote up 4 votes
@Override
public void close() throws IOException {
    DataSourceUtils.releaseConnection(connection, getDataSource());
}
 
Example 62
Project: uranus   File: DBConnectionProviderServiceImpl.java   View Source Code Vote up 4 votes
@Override
public void closeConnection(Connection conn) throws Exception {
	DataSourceUtils.releaseConnection(conn, _ds);
}
 
Example 63
Project: sdcct   File: AbstractDbServer.java   View Source Code Vote up 4 votes
protected void executeInitializationScripts() {
    SdcctDriverDataSource adminDataSrc = null;
    Connection adminConn = null;

    try {
        adminConn = DataSourceUtils.getConnection((adminDataSrc = this.dataSrcConfig.buildDataSource(this.adminUser, true)));

        for (ResourceSource initScriptSrc : this.initScriptSrcs) {
            ScriptUtils
                .executeSqlScript(adminConn,
                    new EncodedResource(new ByteArrayResource(this.embeddedPlaceholderResolver
                        .resolvePlaceholders(new String(initScriptSrc.getBytes(), StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8),
                        initScriptSrc.getResource().getDescription()), StandardCharsets.UTF_8));
        }

        DbUser user = this.dataSrcConfig.getUser();
        String userName = user.getName();
        Map<String, DbRole> roles = user.getRoles();
        StrBuilder secSqlBuilder = new StrBuilder();

        secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getCreateUserString(userName, user.getCredentials()));
        secSqlBuilder.appendNewLine();

        for (String roleName : roles.keySet()) {
            secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getCreateRoleString(roleName));
            secSqlBuilder.appendNewLine();
            secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getGrantRoleString(roleName, userName));

            for (DbAuthority authority : roles.get(roleName).getAuthorities()) {
                secSqlBuilder.appendNewLine();
                secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getGrantOnString(authority, roleName));
            }
        }

        ScriptUtils.executeSqlScript(adminConn,
            new EncodedResource(new ByteArrayResource(secSqlBuilder.build().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

        adminConn.commit();
    } catch (Exception e) {
        throw new HibernateException(String.format("Unable to execute database (name=%s) server (hostAddr=%s, port=%d) initialization scripts.",
            this.dbName, this.hostAddr, this.port), e);
    } finally {
        if (adminConn != null) {
            DataSourceUtils.releaseConnection(adminConn, adminDataSrc);
        }
    }
}
 
Example 64
Project: firefly   File: TemplateGenerator.java   View Source Code Vote up 4 votes
private static void setupFormat(DataGroup template, String querySql, DataSource dataSource) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement(querySql);
            ResultSetMetaData meta = ps.getMetaData();
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                String cname = meta.getColumnName(i);
                DataType dt = template.getDataDefintion(cname);
                if (dt != null) {

                    Class colClass = String.class;
                    try {
                        colClass = Class.forName(meta.getColumnClassName(i));
                    } catch (ClassNotFoundException ex) {
                    }
                    dt.setDataType(colClass);

                    int cwidth = meta.getColumnDisplaySize(i);
                    cwidth = Math.max(cwidth, 6);
                    cwidth = Math.max(cwidth, cname.length());

                    // create format info
                    if (!dt.hasFormatInfo()) {
                        DataType.FormatInfo fInfo = dt.getFormatInfo();
                        String format = null;
                        if (colClass == Float.class || colClass == Double.class) {
                            int scale = Math.max(meta.getScale(i), 6);
                            int prec = Math.max(meta.getPrecision(i), cwidth);
                            format = "%" + prec + "." + scale + "f"; // double or float
                        } else if (Date.class.isAssignableFrom(colClass)) {
                            format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS"; // date
                        }
                        if (format != null) {
                            fInfo.setDataFormat(format);
                        }
                    }

                    dt.getFormatInfo().setWidth(cwidth);

                }
            }
        } finally {
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                DataSourceUtils.releaseConnection(conn, dataSource);
            }
        }
}
 
Example 65
Project: qafe-platform   File: SQLQueryDAO.java   View Source Code Vote up 4 votes
private Object execute(RDBDatasource ds, SQLQuery stmt, Map<String, AdaptedToService> paramsIn, Set outputMapping, Filters filters, DataIdentifier dataId) {
	Long oldChecksum = null;
	if (isConcurrentModificationEnabled()) {
		oldChecksum = ConflictDetectionUtil.removeChecksum(paramsIn);
	}

	String[] inputKeys = null;
	Map<String, Object> paramIns = new HashMap<String, Object>();
	if (paramsIn != null) {
		paramIns = narrow(paramsIn);
		inputKeys = (String[]) paramIns.keySet().toArray(new String[paramIns.size()]);
	}
	MapSqlParameterSource namedParameters = new MapSqlParameterSource(paramIns);
	Object result = null;
	isCountOnly = DataStore.findValue(dataId, DataStore.KEY_WORD_COUNT) != null;
	String sql = QueryToStringCreator.toString(stmt, namedParameters, inputKeys, outputMapping);
	Map values = namedParameters.getValues();
	if ((values != null) && (values.size() > 0)) {
		Map replacementMap = new HashMap<String, Object>();
		for (String key : inputKeys) {
			if (values.containsKey(key.toUpperCase())) {
				replacementMap.put(key, values.get(key.toUpperCase()));
			}
			if (values.containsKey(key.toLowerCase())) {
				replacementMap.put(key, values.get(key.toLowerCase()));
			}
		}
		namedParameters.addValues(replacementMap);
	}
	logger.info("Executing SQL: " + sql);
	SimpleJdbcTemplate template = new SimpleJdbcTemplate(ds.getDataSource());
	try {
		Connection conn = ds.getDataSource().getConnection();
		dialect = getDatabaseDialect(conn);
		DataSourceUtils.releaseConnection(conn, ds.getDataSource());
	} catch (SQLException e) {
		ExceptionHelper.printStackTrace(e);
	}
	if (stmt instanceof Select) {
		result = handleSelect(sql, namedParameters, (Select) stmt, template, filters);
		if (!isCountOnly && isConcurrentModificationEnabled()) {
			ConflictDetectionUtil.addChecksums((List<Map<String, Object>>) result, sql);
		}
	} else if (stmt instanceof Insert) {
		result = handleInsert(sql, namedParameters, (Insert) stmt, template);
		if (isConcurrentModificationEnabled()) {
			DataStore.store(dataId, DataStore.KEY_SERVICE_MODIFY);
		}
	} else if (stmt instanceof SQLOnly) {
		result = handleQueryTag(sql, namedParameters, template);
	} else {
		if (isConcurrentModificationEnabled()) {
			ConflictDetectionUtil.validateChecksum(template, sql, namedParameters.getValues(), oldChecksum);
		}
		template.update(sql, namedParameters);
		if (isConcurrentModificationEnabled()) {
			DataStore.store(dataId, DataStore.KEY_SERVICE_MODIFY);
		}
	}
	return result;
}
 
Example 66
Project: class-guard   File: SqlServerMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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
		* returnes 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() + " default values");
				ResultSet rs = stmt.executeQuery("select @@identity");
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("@@identity 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 increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 67
Project: class-guard   File: DerbyMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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 68
Project: class-guard   File: HsqlMaxValueIncrementer.java   View Source Code Vote up 4 votes
@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() + " values(null)");
				ResultSet rs = stmt.executeQuery("select max(identity()) from " + getIncrementerName());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("identity() 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()", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 69
Project: JServer   File: JdbcDaoComponent.java   View Source Code Vote up 4 votes
/**
 * Close the given JDBC Connection if necessary, created via this bean's
 * DataSource, if it isn't bound to the thread.
 */
protected final void closeConnectionIfNecessary(Connection con) 
{
   DataSourceUtils.releaseConnection(con, getDataSource());
}
 
Example 70
Project: class-guard   File: LocalDataSourceJobStore.java   View Source Code Vote up 4 votes
@Override
protected void closeConnection(Connection con) {
	// Will work for transactional and non-transactional connections.
	DataSourceUtils.releaseConnection(con, this.dataSource);
}
 
Example 71
Project: syncope   File: ProvisioningImpl.java   View Source Code Vote up 4 votes
@Override
public String resolve(final String username) throws ProvisioningException {

    LOG.debug("Resolve request operation received: " + username);

    String resolved = "";

    Connection conn = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);
        PreparedStatement statement =
                conn.prepareStatement("SELECT userId FROM user WHERE userId=?");
        statement.setString(1, username);

        final String query = "SELECT userId FROM user WHERE userId='" + username + "';";

        LOG.debug("Execute query: " + query);

        ResultSet rs = statement.executeQuery();

        resolved = rs.next() ? rs.getString(1) : null;

        statement.close();

        if (resolved == null) {
            statement = conn.prepareStatement("SELECT roleName FROM role WHERE roleName=?");
            statement.setString(1, username);
            final String roleQuery = "SELECT roleName FROM role WHERE roleName='" + username + "';";
            LOG.debug("Execute query: " + roleQuery);

            rs = statement.executeQuery();

            resolved = rs.next() ? rs.getString(1) : null;

            statement.close();
        }
    } catch (SQLException e) {
        throw new ProvisioningException("Resolve operation failed", e);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    return resolved;
}
 
Example 72
Project: springapp   File: SpringConnectionClosingListener.java   View Source Code Vote up 4 votes
@Override
public void end(SQLListenerContext context) {
	DataSourceUtils.releaseConnection(context.getConnection(), dataSource);
}
 
Example 73
Project: CommonDao   File: JdbcTxCommonDao.java   View Source Code Vote up 4 votes
/**
 * 添加支持jdbc datasource Transaction 支持的Connection关闭
 */
@Override
protected void close(Connection conn) throws SQLException {
	DataSourceUtils.releaseConnection(conn, dataSource);
}
 
Example 74
Project: lams   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Close the given JDBC Connection, created via this DAO's DataSource,
 * if it isn't bound to the thread.
 * @param con Connection to close
 * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
 */
protected final void releaseConnection(Connection con) {
	DataSourceUtils.releaseConnection(con, getDataSource());
}
 
Example 75
Project: spring4-understanding   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Close the given JDBC Connection, created via this DAO's DataSource,
 * if it isn't bound to the thread.
 * @param con Connection to close
 * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
 */
protected final void releaseConnection(Connection con) {
	DataSourceUtils.releaseConnection(con, getDataSource());
}
 
Example 76
Project: leopard   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Close the given JDBC Connection, created via this DAO's DataSource, if it isn't bound to the thread.
 * 
 * @param con
 *            Connection to close
 * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
 */
protected final void releaseConnection(Connection con) {
	DataSourceUtils.releaseConnection(con, getDataSource());
}
 
Example 77
Project: leopard-data   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Close the given JDBC Connection, created via this DAO's DataSource, if it isn't bound to the thread.
 * 
 * @param con
 *            Connection to close
 * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
 */
protected final void releaseConnection(Connection con) {
	DataSourceUtils.releaseConnection(con, getDataSource());
}