@NotThreadSafe public class JdbcConnection extends Object implements AutoCloseable
| Modifier and Type | Class and Description |
|---|---|
static interface |
JdbcConnection.BlockingMultiResultSetConsumer |
static interface |
JdbcConnection.BlockingResultSetConsumer |
static interface |
JdbcConnection.CallPreparer |
static interface |
JdbcConnection.ConnectionFactory
Establishes JDBC connections.
|
private class |
JdbcConnection.ConnectionFactoryDecorator |
static interface |
JdbcConnection.MultiResultSetConsumer |
static interface |
JdbcConnection.Operations
Defines multiple JDBC operations.
|
static interface |
JdbcConnection.ParameterResultSetConsumer |
static interface |
JdbcConnection.ResultSetConsumer |
static interface |
JdbcConnection.ResultSetExtractor<T>
Extracts a data of resultset..
|
static interface |
JdbcConnection.ResultSetMapper<T> |
static interface |
JdbcConnection.StatementFactory
A function to create a statement from a connection.
|
static interface |
JdbcConnection.StatementPreparer |
| Modifier and Type | Field and Description |
|---|---|
private Configuration |
config |
private Connection |
conn |
private JdbcConnection.ConnectionFactory |
factory |
private JdbcConnection.Operations |
initialOps |
private static org.slf4j.Logger |
LOGGER |
private static int |
STATEMENT_CACHE_CAPACITY |
private static char |
STATEMENT_DELIMITER |
private Map<String,PreparedStatement> |
statementCache |
private static int |
WAIT_FOR_CLOSE_SECONDS |
| Modifier | Constructor and Description |
|---|---|
|
JdbcConnection(Configuration config,
JdbcConnection.ConnectionFactory connectionFactory)
Create a new instance with the given configuration and connection factory.
|
|
JdbcConnection(Configuration config,
JdbcConnection.ConnectionFactory connectionFactory,
JdbcConnection.Operations initialOperations)
Create a new instance with the given configuration and connection factory, and specify the operations that should be
run against each newly-established connection.
|
protected |
JdbcConnection(Configuration config,
JdbcConnection.ConnectionFactory connectionFactory,
JdbcConnection.Operations initialOperations,
Consumer<Configuration.Builder> adapter)
Create a new instance with the given configuration and connection factory, and specify the operations that should be
run against each newly-established connection.
|
protected |
JdbcConnection(Configuration config,
JdbcConnection.ConnectionFactory connectionFactory,
JdbcConnection.Operations initialOperations,
Consumer<Configuration.Builder> adapter,
Supplier<ClassLoader> classLoaderSupplier)
Create a new instance with the given configuration and connection factory, and specify the operations that should be
run against each newly-established connection.
|
|
JdbcConnection(Configuration config,
JdbcConnection.ConnectionFactory connectionFactory,
Supplier<ClassLoader> classLoaderSupplier)
Create a new instance with the given configuration and connection factory.
|
| Modifier and Type | Method and Description |
|---|---|
JdbcConnection |
call(String sql,
JdbcConnection.CallPreparer callPreparer,
JdbcConnection.ResultSetConsumer resultSetConsumer)
Execute a stored procedure.
|
private void |
cleanupPreparedStatement(PreparedStatement statement) |
void |
close()
Close the connection and release any resources.
|
private static Field[] |
combineVariables(Field[] overriddenVariables,
Field... defaultVariables) |
JdbcConnection |
commit() |
JdbcConfiguration |
config()
Obtain the configuration for this connection.
|
JdbcConnection |
connect()
Ensure a connection to the database is established.
|
Connection |
connection() |
Connection |
connection(boolean executeOnConnect) |
String |
connectionString(String urlPattern)
Returns a JDBC connection string using the current configuration and url.
|
private PreparedStatement |
createPreparedStatement(String preparedQueryString) |
String |
database()
Returns the database name for this connection
|
private String |
delimiter(int columnCount,
int[] columnSizes) |
private void |
doClose() |
JdbcConnection |
execute(JdbcConnection.Operations operations)
Execute a series of operations as a single transaction.
|
JdbcConnection |
execute(String... sqlStatements)
Execute a series of SQL statements as a single transaction.
|
JdbcConnection |
executeWithoutCommitting(String... statements)
Executes a series of statements without explicitly committing the connection.
|
private static String |
findAndReplace(String url,
Properties props,
Field... variables) |
private static String |
findAndReplace(String url,
String name,
Properties props,
String defaultValue) |
private int[] |
findMaxLength(ResultSet resultSet) |
protected Optional<Object> |
getDefaultValue(Column column,
String defaultValue) |
boolean |
isConnected() |
protected static boolean |
isNullable(int jdbcNullable) |
protected List<String> |
parseSqlStatementString(String statements) |
static JdbcConnection.ConnectionFactory |
patternBasedFactory(String urlPattern,
Field... variables)
Create a
JdbcConnection.ConnectionFactory that replaces variables in the supplied URL pattern. |
static JdbcConnection.ConnectionFactory |
patternBasedFactory(String urlPattern,
String driverClassName,
ClassLoader classloader,
Field... variables)
Create a
JdbcConnection.ConnectionFactory that uses the specific JDBC driver class loaded with the given class loader, and obtains the connection URL by replacing the following variables in the URL pattern:
${hostname}
${port}
${dbname}
${username}
${password}
|
JdbcConnection |
prepareQuery(String[] multiQuery,
JdbcConnection.StatementPreparer[] preparers,
JdbcConnection.BlockingMultiResultSetConsumer resultConsumer)
Execute multiple SQL prepared queries where each query is executed with the same set of parameters.
|
JdbcConnection |
prepareQuery(String[] multiQuery,
JdbcConnection.StatementPreparer preparer,
JdbcConnection.BlockingMultiResultSetConsumer resultConsumer)
Execute multiple SQL prepared queries where each query is executed with the same set of parameters.
|
JdbcConnection |
prepareQuery(String preparedQueryString,
JdbcConnection.StatementPreparer preparer,
JdbcConnection.ResultSetConsumer resultConsumer)
Execute a SQL prepared query.
|
JdbcConnection |
prepareQuery(String preparedQueryString,
List<?> parameters,
JdbcConnection.ParameterResultSetConsumer resultConsumer)
Execute a SQL prepared query.
|
<T> T |
prepareQueryAndMap(String preparedQueryString,
JdbcConnection.StatementPreparer preparer,
JdbcConnection.ResultSetMapper<T> mapper)
Execute a SQL prepared query and map the result set into an expected type..
|
JdbcConnection |
prepareQueryWithBlockingConsumer(String preparedQueryString,
JdbcConnection.StatementPreparer preparer,
JdbcConnection.BlockingResultSetConsumer resultConsumer)
Execute a SQL prepared query.
|
JdbcConnection |
prepareUpdate(String stmt,
JdbcConnection.StatementPreparer preparer)
Execute a SQL update via a prepared statement.
|
void |
print(ResultSet resultSet) |
void |
print(ResultSet resultSet,
Consumer<String> lines) |
private static Properties |
propsWithMaskedPassword(Properties props) |
JdbcConnection |
query(String query,
JdbcConnection.ResultSetConsumer resultConsumer)
Execute a SQL query.
|
JdbcConnection |
query(String query,
JdbcConnection.StatementFactory statementFactory,
JdbcConnection.ResultSetConsumer resultConsumer)
Execute a SQL query.
|
<T> T |
queryAndMap(String query,
JdbcConnection.ResultSetMapper<T> mapper)
Execute a SQL query and map the result set into an expected type.
|
<T> T |
queryAndMap(String query,
JdbcConnection.StatementFactory statementFactory,
JdbcConnection.ResultSetMapper<T> mapper)
Execute a SQL query and map the result set into an expected type.
|
static <T> T |
querySingleValue(Connection connection,
String queryString,
JdbcConnection.StatementPreparer preparer,
JdbcConnection.ResultSetExtractor<T> extractor) |
JdbcConnection |
queryWithBlockingConsumer(String query,
JdbcConnection.StatementFactory statementFactory,
JdbcConnection.BlockingResultSetConsumer resultConsumer) |
Set<String> |
readAllCatalogNames()
Get the names of all of the catalogs.
|
Set<String> |
readAllSchemaNames(Predicate<String> filter)
Get the names of all of the schemas, optionally applying a filter.
|
Set<TableId> |
readAllTableNames(String[] tableTypes)
Get the identifiers of all available tables.
|
protected List<String> |
readPrimaryKeyNames(DatabaseMetaData metadata,
TableId id) |
protected List<String> |
readPrimaryKeyOrUniqueIndexNames(DatabaseMetaData metadata,
TableId id) |
void |
readSchema(Tables tables,
String databaseCatalog,
String schemaNamePattern,
Tables.TableFilter tableFilter,
Tables.ColumnNameFilter columnFilter,
boolean removeTablesNotFoundInJdbc)
Create definitions for each tables in the database, given the catalog name, schema pattern, table filter, and
column filter.
|
protected Optional<ColumnEditor> |
readTableColumn(ResultSet columnMetadata,
TableId tableId,
Tables.ColumnNameFilter columnFilter)
Returns a
ColumnEditor representing the current record of the given result set of column metadata, if
included in column.include.list. |
Set<TableId> |
readTableNames(String databaseCatalog,
String schemaNamePattern,
String tableNamePattern,
String[] tableTypes)
Get the identifiers of the tables.
|
List<String> |
readTableUniqueIndices(DatabaseMetaData metadata,
TableId id) |
protected int |
resolveJdbcType(int metadataJdbcType,
int nativeType)
Resolves the supplied metadata JDBC type to a final JDBC type.
|
protected int |
resolveNativeType(String typeName)
Provides a native type for the given type name.
|
JdbcConnection |
rollback() |
JdbcConnection |
setAutoCommit(boolean autoCommit) |
<T> JdbcConnection.ResultSetMapper<T> |
singleResultMapper(JdbcConnection.ResultSetExtractor<T> extractor,
String error) |
String[] |
tableTypes() |
String |
username()
Returns the username for this connection
|
private static final int WAIT_FOR_CLOSE_SECONDS
private static final char STATEMENT_DELIMITER
private static final int STATEMENT_CACHE_CAPACITY
private static final org.slf4j.Logger LOGGER
private final Map<String,PreparedStatement> statementCache
private final Configuration config
private final JdbcConnection.ConnectionFactory factory
private final JdbcConnection.Operations initialOps
private volatile Connection conn
public JdbcConnection(Configuration config, JdbcConnection.ConnectionFactory connectionFactory)
config - the configuration; may not be nullconnectionFactory - the connection factory; may not be nullpublic JdbcConnection(Configuration config, JdbcConnection.ConnectionFactory connectionFactory, Supplier<ClassLoader> classLoaderSupplier)
config - the configuration; may not be nullconnectionFactory - the connection factory; may not be nullpublic JdbcConnection(Configuration config, JdbcConnection.ConnectionFactory connectionFactory, JdbcConnection.Operations initialOperations)
config - the configuration; may not be nullconnectionFactory - the connection factory; may not be nullinitialOperations - the initial operations that should be run on each new connection; may be nullprotected JdbcConnection(Configuration config, JdbcConnection.ConnectionFactory connectionFactory, JdbcConnection.Operations initialOperations, Consumer<Configuration.Builder> adapter)
config - the configuration; may not be nullconnectionFactory - the connection factory; may not be nullinitialOperations - the initial operations that should be run on each new connection; may be nulladapter - the function that can be called to update the configuration with defaultsprotected JdbcConnection(Configuration config, JdbcConnection.ConnectionFactory connectionFactory, JdbcConnection.Operations initialOperations, Consumer<Configuration.Builder> adapter, Supplier<ClassLoader> classLoaderSupplier)
config - the configuration; may not be nullconnectionFactory - the connection factory; may not be nullinitialOperations - the initial operations that should be run on each new connection; may be nulladapter - the function that can be called to update the configuration with defaultsclassLoaderSupplier - class loader supplierpublic static JdbcConnection.ConnectionFactory patternBasedFactory(String urlPattern, Field... variables)
JdbcConnection.ConnectionFactory that replaces variables in the supplied URL pattern. Variables include:
${hostname}${port}${dbname}${username}${password}urlPattern - the URL pattern string; may not be nullvariables - any custom or overridden configuration variablespublic static JdbcConnection.ConnectionFactory patternBasedFactory(String urlPattern, String driverClassName, ClassLoader classloader, Field... variables)
JdbcConnection.ConnectionFactory that uses the specific JDBC driver class loaded with the given class loader, and obtains the connection URL by replacing the following variables in the URL pattern:
${hostname}${port}${dbname}${username}${password}This method attempts to instantiate the JDBC driver class and use that instance to connect to the database.
urlPattern - the URL pattern string; may not be nulldriverClassName - the name of the JDBC driver class; may not be nullclassloader - the ClassLoader that should be used to load the JDBC driver class given by `driverClassName`; may be null if this class' class loader should be usedvariables - any custom or overridden configuration variablesprivate static Properties propsWithMaskedPassword(Properties props)
private static Field[] combineVariables(Field[] overriddenVariables, Field... defaultVariables)
private static String findAndReplace(String url, Properties props, Field... variables)
private static String findAndReplace(String url, String name, Properties props, String defaultValue)
public JdbcConfiguration config()
public JdbcConnection setAutoCommit(boolean autoCommit) throws SQLException
SQLExceptionpublic JdbcConnection commit() throws SQLException
SQLExceptionpublic JdbcConnection rollback() throws SQLException
SQLExceptionpublic JdbcConnection connect() throws SQLException
SQLException - if there is an error connecting to the databasepublic JdbcConnection execute(String... sqlStatements) throws SQLException
sqlStatements - the SQL statements that are to be performed as a single transactionSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public JdbcConnection execute(JdbcConnection.Operations operations) throws SQLException
operations - the function that will be called with a newly-created Statement, and that performs
one or more operations on that statement objectSQLException - if there is an error connecting to the database or executing the statementspublic JdbcConnection query(String query, JdbcConnection.ResultSetConsumer resultConsumer) throws SQLException
query - the SQL queryresultConsumer - the consumer of the query resultsSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public <T> T queryAndMap(String query, JdbcConnection.ResultSetMapper<T> mapper) throws SQLException
T - type returned by the mapperquery - the SQL querymapper - the function processing the query resultsSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public JdbcConnection call(String sql, JdbcConnection.CallPreparer callPreparer, JdbcConnection.ResultSetConsumer resultSetConsumer) throws SQLException
sql - the SQL query; may not be nullcallPreparer - a JdbcConnection.CallPreparer instance which can be used to set additional parameters; may be nullresultSetConsumer - a JdbcConnection.ResultSetConsumer instance which can be used to process the results; may be nullSQLException - if anything unexpected failspublic JdbcConnection query(String query, JdbcConnection.StatementFactory statementFactory, JdbcConnection.ResultSetConsumer resultConsumer) throws SQLException
query - the SQL querystatementFactory - the function that should be used to create the statement from the connection; may not be nullresultConsumer - the consumer of the query resultsSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public JdbcConnection prepareQuery(String[] multiQuery, JdbcConnection.StatementPreparer preparer, JdbcConnection.BlockingMultiResultSetConsumer resultConsumer) throws SQLException, InterruptedException
multiQuery - the array of prepared queriespreparer - the function that supplies arguments to the prepared statement; may not be nullresultConsumer - the consumer of the query resultsSQLException - if there is an error connecting to the database or executing the statementsInterruptedExceptionexecute(Operations)public JdbcConnection prepareQuery(String[] multiQuery, JdbcConnection.StatementPreparer[] preparers, JdbcConnection.BlockingMultiResultSetConsumer resultConsumer) throws SQLException, InterruptedException
multiQuery - the array of prepared queriespreparers - the array of functions that supply arguments to the prepared statements; may not be nullresultConsumer - the consumer of the query resultsSQLException - if there is an error connecting to the database or executing the statementsInterruptedExceptionexecute(Operations)public <T> T queryAndMap(String query, JdbcConnection.StatementFactory statementFactory, JdbcConnection.ResultSetMapper<T> mapper) throws SQLException
T - type returned by the mapperquery - the SQL querystatementFactory - the function that should be used to create the statement from the connection; may not be nullmapper - the function processing the query resultsSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public JdbcConnection queryWithBlockingConsumer(String query, JdbcConnection.StatementFactory statementFactory, JdbcConnection.BlockingResultSetConsumer resultConsumer) throws SQLException, InterruptedException
SQLExceptionInterruptedExceptionpublic JdbcConnection prepareQueryWithBlockingConsumer(String preparedQueryString, JdbcConnection.StatementPreparer preparer, JdbcConnection.BlockingResultSetConsumer resultConsumer) throws SQLException, InterruptedException
preparedQueryString - the prepared query stringpreparer - the function that supplied arguments to the prepared statement; may not be nullresultConsumer - the consumer of the query resultsSQLException - if there is an error connecting to the database or executing the statementsInterruptedExceptionexecute(Operations)public JdbcConnection prepareQuery(String preparedQueryString, JdbcConnection.StatementPreparer preparer, JdbcConnection.ResultSetConsumer resultConsumer) throws SQLException
preparedQueryString - the prepared query stringpreparer - the function that supplied arguments to the prepared statement; may not be nullresultConsumer - the consumer of the query resultsSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public <T> T prepareQueryAndMap(String preparedQueryString, JdbcConnection.StatementPreparer preparer, JdbcConnection.ResultSetMapper<T> mapper) throws SQLException
T - type returned by the mapperpreparedQueryString - the prepared query stringpreparer - the function that supplied arguments to the prepared statement; may not be nullmapper - the function processing the query resultsSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public JdbcConnection prepareUpdate(String stmt, JdbcConnection.StatementPreparer preparer) throws SQLException
stmt - the statement stringpreparer - the function that supplied arguments to the prepared stmt; may be nullSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public JdbcConnection prepareQuery(String preparedQueryString, List<?> parameters, JdbcConnection.ParameterResultSetConsumer resultConsumer) throws SQLException
preparedQueryString - the prepared query stringparameters - the list of values for parameters in the query; may not be nullresultConsumer - the consumer of the query resultsSQLException - if there is an error connecting to the database or executing the statementsexecute(Operations)public void print(ResultSet resultSet)
private String delimiter(int columnCount, int[] columnSizes)
private int[] findMaxLength(ResultSet resultSet) throws SQLException
SQLExceptionpublic boolean isConnected()
throws SQLException
SQLExceptionpublic Connection connection() throws SQLException
SQLExceptionpublic Connection connection(boolean executeOnConnect) throws SQLException
SQLExceptionpublic void close()
throws SQLException
close in interface AutoCloseableSQLExceptionprivate void doClose()
throws SQLException
SQLExceptionpublic Set<String> readAllCatalogNames() throws SQLException
SQLException - if an error occurs while accessing the database metadatapublic Set<String> readAllSchemaNames(Predicate<String> filter) throws SQLException
filter - a Predicate to test each schema name; may be null in which case all schema names are returnedSQLException - if an error occurs while accessing the database metadatapublic String[] tableTypes() throws SQLException
SQLExceptionpublic Set<TableId> readAllTableNames(String[] tableTypes) throws SQLException
tableTypes - the set of table types to include in the results, which may be null for all table typesTableIds; never null but possibly emptySQLException - if an error occurs while accessing the database metadatapublic Set<TableId> readTableNames(String databaseCatalog, String schemaNamePattern, String tableNamePattern, String[] tableTypes) throws SQLException
databaseCatalog - the name of the catalog, which is typically the database name; may be an empty string for tables
that have no catalog, or null if the catalog name should not be used to narrow the list of table
identifiersschemaNamePattern - the pattern used to match database schema names, which may be "" to match only those tables with
no schema or null if the schema name should not be used to narrow the list of table
identifierstableNamePattern - the pattern used to match database table names, which may be null to match all table namestableTypes - the set of table types to include in the results, which may be null for all table typesTableIds; never null but possibly emptySQLException - if an error occurs while accessing the database metadatapublic String connectionString(String urlPattern)
urlPattern - a String representing a JDBC connection with variables that will be replacedString where the variables in urlPattern are replaced with values from the configurationpublic String username()
String, never nullpublic String database()
String, never nullprotected int resolveNativeType(String typeName)
typeName - the name of the type whose native type we are looking forprotected int resolveJdbcType(int metadataJdbcType,
int nativeType)
metadataJdbcType - the JDBC type from the underlying driver's metadata lookupnativeType - the database native type or -1 for unknownpublic void readSchema(Tables tables, String databaseCatalog, String schemaNamePattern, Tables.TableFilter tableFilter, Tables.ColumnNameFilter columnFilter, boolean removeTablesNotFoundInJdbc) throws SQLException
tables - the set of table definitions to be modified; may not be nulldatabaseCatalog - the name of the catalog, which is typically the database name; may be null if all accessible
databases are to be processedschemaNamePattern - the pattern used to match database schema names, which may be "" to match only those tables with
no schema or null to process all accessible tables regardless of database schema nametableFilter - used to determine for which tables are to be processed; may be null if all accessible tables are to be
processedcolumnFilter - used to determine which columns should be included as fields in its table's definition; may
be null if all columns for all tables are to be includedremoveTablesNotFoundInJdbc - true if this method should remove from tables any definitions for tables
that are not found in the database metadata, or false if such tables should be left untouchedSQLException - if an error occurs while accessing the database metadataprotected Optional<ColumnEditor> readTableColumn(ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnFilter) throws SQLException
ColumnEditor representing the current record of the given result set of column metadata, if
included in column.include.list.SQLExceptionprotected List<String> readPrimaryKeyNames(DatabaseMetaData metadata, TableId id) throws SQLException
SQLExceptionpublic List<String> readTableUniqueIndices(DatabaseMetaData metadata, TableId id) throws SQLException
SQLExceptionprotected List<String> readPrimaryKeyOrUniqueIndexNames(DatabaseMetaData metadata, TableId id) throws SQLException
SQLExceptionprivate void cleanupPreparedStatement(PreparedStatement statement)
private PreparedStatement createPreparedStatement(String preparedQueryString)
public JdbcConnection executeWithoutCommitting(String... statements) throws SQLException
statements - a series of statements to executeSQLException - if anything failsprotected static boolean isNullable(int jdbcNullable)
public <T> JdbcConnection.ResultSetMapper<T> singleResultMapper(JdbcConnection.ResultSetExtractor<T> extractor, String error) throws SQLException
SQLExceptionpublic static <T> T querySingleValue(Connection connection, String queryString, JdbcConnection.StatementPreparer preparer, JdbcConnection.ResultSetExtractor<T> extractor) throws SQLException
SQLExceptionCopyright © 2020 JBoss by Red Hat. All rights reserved.