Java Code Examples for org.springframework.jdbc.support.JdbcUtils

The following examples show how to use org.springframework.jdbc.support.JdbcUtils. These examples are extracted from open source projects. 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
/**
 * 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 Project: spring-analysis-note   Source File: RowCountCallbackHandler.java    License: MIT License 6 votes vote down vote up
/**
 * Implementation of ResultSetCallbackHandler.
 * Work out column size if this is the first row, otherwise just count rows.
 * <p>Subclasses can perform custom extraction or processing
 * by overriding the {@code processRow(ResultSet, int)} method.
 * @see #processRow(java.sql.ResultSet, int)
 */
@Override
public final void processRow(ResultSet rs) throws SQLException {
	if (this.rowCount == 0) {
		ResultSetMetaData rsmd = rs.getMetaData();
		this.columnCount = rsmd.getColumnCount();
		this.columnTypes = new int[this.columnCount];
		this.columnNames = new String[this.columnCount];
		for (int i = 0; i < this.columnCount; i++) {
			this.columnTypes[i] = rsmd.getColumnType(i + 1);
			this.columnNames[i] = JdbcUtils.lookupColumnName(rsmd, i + 1);
		}
		// could also get column names
	}
	processRow(rs, this.rowCount++);
}
 
Example 3
Source Project: bdf3   Source File: DbCommonServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<String> findTablePrimaryKeys(String dbInfoId, String tableName) throws Exception {
	List<String> primaryKeys = new ArrayList<String>();
	Connection con = null;
	ResultSet rs = null;
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	try {
		con = ds.getConnection();
		DatabaseMetaData metaData = con.getMetaData();
		rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
		while (rs.next()) {
			primaryKeys.add(rs.getString("COLUMN_NAME").toUpperCase());
		}
		return primaryKeys;
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeConnection(con);
	}
}
 
Example 4
/**
 * 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 5
Source Project: java-technology-stack   Source File: RowCountCallbackHandler.java    License: MIT License 6 votes vote down vote up
/**
 * Implementation of ResultSetCallbackHandler.
 * Work out column size if this is the first row, otherwise just count rows.
 * <p>Subclasses can perform custom extraction or processing
 * by overriding the {@code processRow(ResultSet, int)} method.
 * @see #processRow(java.sql.ResultSet, int)
 */
@Override
public final void processRow(ResultSet rs) throws SQLException {
	if (this.rowCount == 0) {
		ResultSetMetaData rsmd = rs.getMetaData();
		this.columnCount = rsmd.getColumnCount();
		this.columnTypes = new int[this.columnCount];
		this.columnNames = new String[this.columnCount];
		for (int i = 0; i < this.columnCount; i++) {
			this.columnTypes[i] = rsmd.getColumnType(i + 1);
			this.columnNames[i] = JdbcUtils.lookupColumnName(rsmd, i + 1);
		}
		// could also get column names
	}
	processRow(rs, this.rowCount++);
}
 
Example 6
Source Project: bdf3   Source File: DbCommonServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<String> findDefaultColumnType(String dbInfoId) throws Exception {
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	Connection conn = null;
	ResultSet resultSet = null;
	try {
		conn = DataSourceUtils.getConnection(ds);
		DatabaseMetaData metaData = conn.getMetaData();
		resultSet = metaData.getTypeInfo();
		List<String> list = new ArrayList<String>();
		while (resultSet.next()) {
			String typeName = resultSet.getString("TYPE_NAME").toUpperCase();
			list.add(typeName);
		}
		return list;
	} finally {
		JdbcUtils.closeResultSet(resultSet);
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 7
/**
 * 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 8
Source Project: DataLink   Source File: DdlUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static List<Column> generateColumns(DatabaseMetaDataWrapper metaData, String tableName) throws SQLException {
    ResultSet columnsResultSet = null;

    try {
        columnsResultSet = metaData.getColumns(tableName, null);

        List<Column> columns = new ArrayList<>();
        Map<String, Object> values;

        for (; columnsResultSet.next(); columns.add(generateOneColumn(metaData, values))) {
            Map<String, Object> tmp = readColumns(columnsResultSet, getDescriptorsForColumn());
            if (tableName.equalsIgnoreCase((String) tmp.get("TABLE_NAME"))) {
                values = tmp;
            } else {
                break;
            }
        }

        return columns;
    } finally {
        JdbcUtils.closeResultSet(columnsResultSet);
    }
}
 
Example 9
Source Project: DataLink   Source File: DdlUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Collection<String> readPrimaryKeyNames(DatabaseMetaDataWrapper metaData, String tableName)
        throws SQLException {
    ResultSet pkData = null;

    try {
        List<String> pks = new ArrayList<>();
        Map<String, Object> values;

        for (pkData = metaData.getPrimaryKeys(tableName); pkData.next(); pks.add(readPrimaryKeyName(metaData,
                values))) {
            values = readColumns(pkData, getDescriptorsForPK());
        }

        return pks;
    } finally {
        JdbcUtils.closeResultSet(pkData);
    }
}
 
Example 10
Source Project: DataLink   Source File: DdlUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static List<Index> generateIndices(DatabaseMetaDataWrapper metaData, String tableName) throws SQLException {
    List<Index> indexes = new ArrayList<>();
    ResultSet indicesResultSet = null;

    try {
        indicesResultSet = metaData.getIndices(tableName, true, false);
        Map<String, Object> values;
        for (; indicesResultSet.next(); generateOneIndex(metaData, values, indexes)) {
            Map<String, Object> tmp = readColumns(indicesResultSet, getDescriptorsForIndex());
            if (tableName.equalsIgnoreCase((String) tmp.get("TABLE_NAME"))) {
                values = tmp;
            } else {
                break;
            }
        }
    } finally {
        JdbcUtils.closeResultSet(indicesResultSet);
    }

    return indexes;
}
 
Example 11
Source Project: EasyTransaction   Source File: IdempotentHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws java.sql.SQLException {

	ResultSetMetaData metaData = rs.getMetaData();
	String columnName = metaData.getColumnName(index).toLowerCase();
	switch(columnName) {
		case "src_app_id":
		case "app_id":
		case "handler":
			return transform(rs, index, APP_ID);
		case "src_bus_code":
		case "bus_code":
			return transform(rs, index, BUSINESS_CODE);
		case "called_methods":
			return id2callMethodsString((String) JdbcUtils.getResultSetValue(rs, index, String.class));
		case "md5":
			byte[] md5Bytes = (byte[]) JdbcUtils.getResultSetValue(rs, index, byte[].class);
			return ObjectDigestUtil.byteArrayToHexString(md5Bytes);
		default:
			return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
	}
}
 
Example 12
/**
 * 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 13
Source Project: lams   Source File: RowCountCallbackHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Work out column size if this is the first row, otherwise just count rows.
 * <p>Subclasses can perform custom extraction or processing
 * by overriding the {@code processRow(ResultSet, int)} method.
 * @see #processRow(java.sql.ResultSet, int)
 */
@Override
public final void processRow(ResultSet rs) throws SQLException {
	if (this.rowCount == 0) {
		ResultSetMetaData rsmd = rs.getMetaData();
		this.columnCount = rsmd.getColumnCount();
		this.columnTypes = new int[this.columnCount];
		this.columnNames = new String[this.columnCount];
		for (int i = 0; i < this.columnCount; i++) {
			this.columnTypes[i] = rsmd.getColumnType(i + 1);
			this.columnNames[i] = JdbcUtils.lookupColumnName(rsmd, i + 1);
		}
		// could also get column names
	}
	processRow(rs, this.rowCount++);
}
 
Example 14
/**
 * Execute the given schema script on the given JDBC Connection.
 * <p>Note that the default implementation will log unsuccessful statements
 * and continue to execute. Override the {@code executeSchemaStatement}
 * method to treat failures differently.
 * @param con the JDBC Connection to execute the script on
 * @param sql the SQL statements to execute
 * @throws SQLException if thrown by JDBC methods
 * @see #executeSchemaStatement
 */
protected void executeSchemaScript(Connection con, String[] sql) throws SQLException {
	if (sql != null && sql.length > 0) {
		boolean oldAutoCommit = con.getAutoCommit();
		if (!oldAutoCommit) {
			con.setAutoCommit(true);
		}
		try {
			Statement stmt = con.createStatement();
			try {
				for (String sqlStmt : sql) {
					executeSchemaStatement(stmt, sqlStmt);
				}
			}
			finally {
				JdbcUtils.closeStatement(stmt);
			}
		}
		finally {
			if (!oldAutoCommit) {
				con.setAutoCommit(false);
			}
		}
	}
}
 
Example 15
@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 16
Source Project: spring-analysis-note   Source File: JdbcTemplate.java    License: 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 17
Source Project: spring-analysis-note   Source File: JdbcTemplate.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public <T> T query(final String sql, final ResultSetExtractor<T> rse) throws DataAccessException {
	Assert.notNull(sql, "SQL must not be null");
	Assert.notNull(rse, "ResultSetExtractor must not be null");
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SQL query [" + sql + "]");
	}

	/**
	 * Callback to execute the query.
	 */
	class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
		@Override
		@Nullable
		public T doInStatement(Statement stmt) throws SQLException {
			ResultSet rs = null;
			try {
				rs = stmt.executeQuery(sql);
				return rse.extractData(rs);
			}
			finally {
				JdbcUtils.closeResultSet(rs);
			}
		}
		@Override
		public String getSql() {
			return sql;
		}
	}

	return execute(new QueryStatementCallback());
}
 
Example 18
Source Project: score   Source File: ExecutionQueueRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
private String getDatabaseProductName() {
    String dbms = "";
    try {
        dbms = (String) JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");

        logger.info("Database product name: " + dbms);
    } catch (MetaDataAccessException e) {
        logger.warn("Database type could not be determined!", e);
    }

    return dbms;
}
 
Example 19
Source Project: spring4-understanding   Source File: JdbcTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int update(final PreparedStatementCreator psc, final KeyHolder generatedKeyHolder)
		throws DataAccessException {

	Assert.notNull(generatedKeyHolder, "KeyHolder must not be null");
	logger.debug("Executing SQL update and returning generated keys");

	return execute(psc, new PreparedStatementCallback<Integer>() {
		@Override
		public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
			int rows = ps.executeUpdate();
			List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList();
			generatedKeys.clear();
			ResultSet keys = ps.getGeneratedKeys();
			if (keys != null) {
				try {
					RowMapperResultSetExtractor<Map<String, Object>> rse =
							new RowMapperResultSetExtractor<Map<String, Object>>(getColumnMapRowMapper(), 1);
					generatedKeys.addAll(rse.extractData(keys));
				}
				finally {
					JdbcUtils.closeResultSet(keys);
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
			}
			return rows;
		}
	});
}
 
Example 20
Source Project: spring-analysis-note   Source File: AbstractSqlParameterSource.java    License: MIT License 5 votes vote down vote up
/**
 * Enumerate the parameter names and values with their corresponding SQL type if available,
 * or just return the simple {@code SqlParameterSource} implementation class name otherwise.
 * @since 5.2
 * @see #getParameterNames()
 */
@Override
public String toString() {
	String[] parameterNames = getParameterNames();
	if (parameterNames != null) {
		StringJoiner result = new StringJoiner(", ", getClass().getSimpleName() + " {", "}");
		for (String parameterName : parameterNames) {
			Object value = getValue(parameterName);
			if (value instanceof SqlParameterValue) {
				value = ((SqlParameterValue) value).getValue();
			}
			String typeName = getTypeName(parameterName);
			if (typeName == null) {
				int sqlType = getSqlType(parameterName);
				if (sqlType != TYPE_UNKNOWN) {
					typeName = JdbcUtils.resolveTypeName(sqlType);
					if (typeName == null) {
						typeName = String.valueOf(sqlType);
					}
				}
			}
			StringBuilder entry = new StringBuilder();
			entry.append(parameterName).append('=').append(value);
			if (typeName != null) {
				entry.append(" (type:").append(typeName).append(')');
			}
			result.add(entry);
		}
		return result.toString();
	}
	else {
		return getClass().getSimpleName();
	}
}
 
Example 21
private boolean versionTableExist() {
  try {
    return (boolean)
        JdbcUtils.extractDatabaseMetaData(
            dataSource,
            dbmd -> {
              ResultSet tables = dbmd.getTables(null, null, "Version", new String[] {"TABLE"});
              return tables.first();
            });
  } catch (MetaDataAccessException e) {
    return false;
  }
}
 
Example 22
Source Project: spring-analysis-note   Source File: TableMetaDataContext.java    License: MIT License 5 votes vote down vote up
/**
 * Match the provided column names and values with the list of columns used.
 * @param parameterSource the parameter names and values
 */
public List<Object> matchInParameterValuesWithInsertColumns(SqlParameterSource parameterSource) {
	List<Object> values = new ArrayList<>();
	// For parameter source lookups we need to provide case-insensitive lookup support since the
	// database meta-data is not necessarily providing case-sensitive column names
	Map<String, String> caseInsensitiveParameterNames =
			SqlParameterSourceUtils.extractCaseInsensitiveParameterNames(parameterSource);
	for (String column : this.tableColumns) {
		if (parameterSource.hasValue(column)) {
			values.add(SqlParameterSourceUtils.getTypedValue(parameterSource, column));
		}
		else {
			String lowerCaseName = column.toLowerCase();
			if (parameterSource.hasValue(lowerCaseName)) {
				values.add(SqlParameterSourceUtils.getTypedValue(parameterSource, lowerCaseName));
			}
			else {
				String propertyName = JdbcUtils.convertUnderscoreNameToPropertyName(column);
				if (parameterSource.hasValue(propertyName)) {
					values.add(SqlParameterSourceUtils.getTypedValue(parameterSource, propertyName));
				}
				else {
					if (caseInsensitiveParameterNames.containsKey(lowerCaseName)) {
						values.add(SqlParameterSourceUtils.getTypedValue(
								parameterSource, caseInsensitiveParameterNames.get(lowerCaseName)));
					}
					else {
						values.add(null);
					}
				}
			}
		}
	}
	return values;
}
 
Example 23
Source Project: spring-analysis-note   Source File: ColumnMapRowMapper.java    License: MIT License 5 votes vote down vote up
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
	ResultSetMetaData rsmd = rs.getMetaData();
	int columnCount = rsmd.getColumnCount();
	Map<String, Object> mapOfColumnValues = createColumnMap(columnCount);
	for (int i = 1; i <= columnCount; i++) {
		String column = JdbcUtils.lookupColumnName(rsmd, i);
		mapOfColumnValues.putIfAbsent(getColumnKey(column), getColumnValue(rs, i));
	}
	return mapOfColumnValues;
}
 
Example 24
Source Project: effectivejava   Source File: JdbcTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int update(final PreparedStatementCreator psc, final KeyHolder generatedKeyHolder)
		throws DataAccessException {

	Assert.notNull(generatedKeyHolder, "KeyHolder must not be null");
	logger.debug("Executing SQL update and returning generated keys");

	return execute(psc, new PreparedStatementCallback<Integer>() {
		@Override
		public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
			int rows = ps.executeUpdate();
			List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList();
			generatedKeys.clear();
			ResultSet keys = ps.getGeneratedKeys();
			if (keys != null) {
				try {
					RowMapperResultSetExtractor<Map<String, Object>> rse =
							new RowMapperResultSetExtractor<Map<String, Object>>(getColumnMapRowMapper(), 1);
					generatedKeys.addAll(rse.extractData(keys));
				}
				finally {
					JdbcUtils.closeResultSet(keys);
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
			}
			return rows;
		}
	});
}
 
Example 25
Source Project: Milkomeda   Source File: CamelCaseColumnMapRowMapper.java    License: MIT License 5 votes vote down vote up
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Map<String, Object> mapOfColumnValues = createColumnMap(columnCount);
    for (int i = 1; i <= columnCount; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i);
        mapOfColumnValues.putIfAbsent(DataTypeConvertUtil.toCamelCase(getColumnKey(column)), getColumnValue(rs, i));
    }
    return mapOfColumnValues;
}
 
Example 26
@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 27
Source Project: ureport   Source File: DatasourceServletAction.java    License: Apache License 2.0 5 votes vote down vote up
public void buildDatabaseTables(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	Connection conn=null;
	ResultSet rs = null;
	try{
		conn=buildConnection(req);
		DatabaseMetaData metaData = conn.getMetaData();
		String url = metaData.getURL();
		String schema = null;
		if (url.toLowerCase().contains("oracle")) {
			schema = metaData.getUserName();
		}
		List<Map<String,String>> tables = new ArrayList<Map<String,String>>();
		rs = metaData.getTables(null, schema, "%", new String[] { "TABLE","VIEW" });
		while (rs.next()) {
			Map<String,String> table = new HashMap<String,String>();
			table.put("name",rs.getString("TABLE_NAME"));
			table.put("type",rs.getString("TABLE_TYPE"));
			tables.add(table);
		}
		writeObjectToJson(resp, tables);
	}catch(Exception ex){
		throw new ServletException(ex);
	}finally{
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 28
Source Project: java-technology-stack   Source File: JdbcTemplate.java    License: 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 29
Source Project: java-technology-stack   Source File: JdbcTemplate.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public <T> T query(final String sql, final ResultSetExtractor<T> rse) throws DataAccessException {
	Assert.notNull(sql, "SQL must not be null");
	Assert.notNull(rse, "ResultSetExtractor must not be null");
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SQL query [" + sql + "]");
	}

	/**
	 * Callback to execute the query.
	 */
	class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
		@Override
		@Nullable
		public T doInStatement(Statement stmt) throws SQLException {
			ResultSet rs = null;
			try {
				rs = stmt.executeQuery(sql);
				return rse.extractData(rs);
			}
			finally {
				JdbcUtils.closeResultSet(rs);
			}
		}
		@Override
		public String getSql() {
			return sql;
		}
	}

	return execute(new QueryStatementCallback());
}
 
Example 30
Source Project: java-technology-stack   Source File: JdbcTemplate.java    License: MIT License 5 votes vote down vote up
@Override
public int update(final PreparedStatementCreator psc, final KeyHolder generatedKeyHolder)
		throws DataAccessException {

	Assert.notNull(generatedKeyHolder, "KeyHolder must not be null");
	logger.debug("Executing SQL update and returning generated keys");

	return updateCount(execute(psc, ps -> {
		int rows = ps.executeUpdate();
		List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList();
		generatedKeys.clear();
		ResultSet keys = ps.getGeneratedKeys();
		if (keys != null) {
			try {
				RowMapperResultSetExtractor<Map<String, Object>> rse =
						new RowMapperResultSetExtractor<>(getColumnMapRowMapper(), 1);
				generatedKeys.addAll(result(rse.extractData(keys)));
			}
			finally {
				JdbcUtils.closeResultSet(keys);
			}
		}
		if (logger.isTraceEnabled()) {
			logger.trace("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
		}
		return rows;
	}));
}