org.springframework.jdbc.support.JdbcUtils Java Examples

The following examples show how to use org.springframework.jdbc.support.JdbcUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractSequenceMaxValueIncrementer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #2
Source File: RowCountCallbackHandler.java    From spring-analysis-note with 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 File: AbstractSequenceMaxValueIncrementer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #4
Source File: DbCommonServiceImpl.java    From bdf3 with 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 #5
Source File: RowCountCallbackHandler.java    From java-technology-stack with 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 File: DbCommonServiceImpl.java    From bdf3 with 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
Source File: AbstractSequenceMaxValueIncrementer.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #8
Source File: DdlUtils.java    From DataLink with 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 File: DdlUtils.java    From DataLink with 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 File: DdlUtils.java    From DataLink with 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 File: IdempotentHelper.java    From EasyTransaction with 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
Source File: AbstractSequenceMaxValueIncrementer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #13
Source File: RowCountCallbackHandler.java    From lams with 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
Source File: LocalSessionFactoryBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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
Source File: GenericTableMetaDataProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method supporting the metadata processing for a table.
 */
private void locateTableAndProcessMetaData(
		DatabaseMetaData databaseMetaData, String catalogName, String schemaName, String tableName) {

	Map<String, TableMetaData> tableMeta = new HashMap<String, TableMetaData>();
	ResultSet tables = null;
	try {
		tables = databaseMetaData.getTables(
				catalogNameToUse(catalogName), schemaNameToUse(schemaName), tableNameToUse(tableName), null);
		while (tables != null && tables.next()) {
			TableMetaData tmd = new TableMetaData();
			tmd.setCatalogName(tables.getString("TABLE_CAT"));
			tmd.setSchemaName(tables.getString("TABLE_SCHEM"));
			tmd.setTableName(tables.getString("TABLE_NAME"));
			if (tmd.getSchemaName() == null) {
				tableMeta.put(this.userName != null ? this.userName.toUpperCase() : "", tmd);
			}
			else {
				tableMeta.put(tmd.getSchemaName().toUpperCase(), tmd);
			}
		}
	}
	catch (SQLException ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Error while accessing table meta data results: " + ex.getMessage());
		}
	}
	finally {
		JdbcUtils.closeResultSet(tables);
	}

	if (tableMeta.isEmpty()) {
		if (logger.isWarnEnabled()) {
			logger.warn("Unable to locate table meta data for '" + tableName + "': column names must be provided");
		}
	}
	else {
		processTableColumns(databaseMetaData, findTableMetaData(schemaName, tableName, tableMeta));
	}
}
 
Example #16
Source File: MolgenisVersionService.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #17
Source File: ProcedureJdbcTemplate.java    From opscenter with Apache License 2.0 5 votes vote down vote up
/**
 * 执行存储过程
 * @param psc
 * @param rsStatus
 * @param outParam
 * @return T
 * @throws DataAccessException
 */
@Nullable
private <T> T execProcedure(CallableStatementCreator csc,boolean rsStatus,String[] outParam)	throws DataAccessException {
	return namedParameterJdbcTemplate.getJdbcTemplate().execute(csc, new CallableStatementCallback<T>() {
		@SuppressWarnings("unchecked")
		@Override
		public T doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
			Map<String,Object> result = new HashMap<String, Object>();
			Map<String,Object> message = new HashMap<String, Object>();
			ResultSet rs = null;
			boolean sqlExecuteStatus = false;
			int outParamLen = outParam.length;
			try {
				if(rsStatus) {
					rs = cs.executeQuery();
					result.put("rows", createRows(cs, rs));
					sqlExecuteStatus = true;
				}else {
					sqlExecuteStatus = cs.execute();
				}
				for (int i = 0; i <  outParamLen; i++) {
					message.put(outParam[i], cs.getString(outParam[i]));
				}
				message.put("sqlExecuteStatus", sqlExecuteStatus);
				result.put("message", message);
			} catch (IOException e) {
			}finally {
				JdbcUtils.closeResultSet(rs);
			}
			return (T) result;
		}
	});
}
 
Example #18
Source File: JdbcTemplate.java    From spring-analysis-note with 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 #19
Source File: JdbcTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(obtainDataSource());
	Statement stmt = null;
	try {
		stmt = con.createStatement();
		applyStatementSettings(stmt);
		T result = action.doInStatement(stmt);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		String sql = getSql(action);
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw translateException("StatementCallback", sql, ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #20
Source File: SkipperFlywayConfigurationCustomizer.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
private DatabaseDriver getDatabaseDriver(DataSource dataSource) {
	// copied from boot's flyway auto-config to get matching db vendor id
	try {
		String url = JdbcUtils.extractDatabaseMetaData(dataSource, "getURL");
		return DatabaseDriver.fromJdbcUrl(url);
	}
	catch (MetaDataAccessException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example #21
Source File: ExecutionQueueRepositoryImpl.java    From score with 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 #22
Source File: TableMetaDataContext.java    From java-technology-stack with 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 File: MaxValueIncrementerFactory.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected synchronized long getNextKey() throws DataAccessException {
    return template.execute(new ConnectionCallback<Long>() {
        @Override
        public Long doInConnection(Connection con) throws SQLException, DataAccessException {
            Statement statement = null;
            ResultSet resultSet = null;
            try {
                statement = con.createStatement();
                String sql = "INSERT INTO " + getIncrementerName() + " VALUES (NULL)";
                statement.executeUpdate(sql);
                sql = "SELECT LAST_INSERT_ID()";
                resultSet = statement.executeQuery(sql);
                if (resultSet != null) {
                    resultSet.first();
                    return resultSet.getLong(1);
                } else {
                    throw new IncorrectResultSizeDataAccessException("Failed to get last_insert_id() for sequence incrementer table '" + getIncrementerName() + "'", 1);
                }
            } finally {
                JdbcUtils.closeResultSet(resultSet);
                JdbcUtils.closeStatement(statement);
            }
        }
    }).longValue();
}
 
Example #24
Source File: ResultSetAccessor.java    From compass with Apache License 2.0 5 votes vote down vote up
public Object getFieldValue(String field)  {
Integer index = fieldIndex.get(field);

if (index == null || index.intValue() < 0) {
	throw new IllegalArgumentException("invalid field=" + field);
}

try {
	return JdbcUtils.getResultSetValue(resultSet, index);
} catch (SQLException e) {
	throw new SQLExceptionCarrier(e);
}
  }
 
Example #25
Source File: GenericTableMetaDataProvider.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Method supporting the meta-data processing for a table.
 */
private void locateTableAndProcessMetaData(DatabaseMetaData databaseMetaData,
		@Nullable String catalogName, @Nullable String schemaName, @Nullable String tableName) {

	Map<String, TableMetaData> tableMeta = new HashMap<>();
	ResultSet tables = null;
	try {
		tables = databaseMetaData.getTables(
				catalogNameToUse(catalogName), schemaNameToUse(schemaName), tableNameToUse(tableName), null);
		while (tables != null && tables.next()) {
			TableMetaData tmd = new TableMetaData();
			tmd.setCatalogName(tables.getString("TABLE_CAT"));
			tmd.setSchemaName(tables.getString("TABLE_SCHEM"));
			tmd.setTableName(tables.getString("TABLE_NAME"));
			if (tmd.getSchemaName() == null) {
				tableMeta.put(this.userName != null ? this.userName.toUpperCase() : "", tmd);
			}
			else {
				tableMeta.put(tmd.getSchemaName().toUpperCase(), tmd);
			}
		}
	}
	catch (SQLException ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Error while accessing table meta-data results: " + ex.getMessage());
		}
	}
	finally {
		JdbcUtils.closeResultSet(tables);
	}

	if (tableMeta.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info("Unable to locate table meta-data for '" + tableName + "': column names must be provided");
		}
	}
	else {
		processTableColumns(databaseMetaData, findTableMetaData(schemaName, tableName, tableMeta));
	}
}
 
Example #26
Source File: JdbcTransactionRepository.java    From galaxy with Apache License 2.0 5 votes vote down vote up
private void closeStatement(Statement stmt) {
	try {
		JdbcUtils.closeStatement(stmt);
		stmt = null;
	} catch (Exception ex) {
		//throw new DistributedTransactionException(ex);
	}
}
 
Example #27
Source File: JdbcTemplate.java    From java-technology-stack with 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;
	}));
}
 
Example #28
Source File: JdbcTemplate.java    From java-technology-stack with 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 #29
Source File: JdbcTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(obtainDataSource());
	Statement stmt = null;
	try {
		stmt = con.createStatement();
		applyStatementSettings(stmt);
		T result = action.doInStatement(stmt);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		String sql = getSql(action);
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw translateException("StatementCallback", sql, ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #30
Source File: JdbcTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (this.nativeJdbcExtractor != null &&
				this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
		}
		stmt = conToUse.createStatement();
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (this.nativeJdbcExtractor != null) {
			stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
		}
		T result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}