public class DB extends Object implements Closeable
Base
such that in this class you
can provide a logical name for a current connection. Use this class when you have more than one database in the system.Modifier and Type | Field and Description |
---|---|
static String |
DEFAULT_NAME |
Constructor and Description |
---|
DB()
Creates a new DB object representing a connection to a DB with default name.
|
DB(String name)
Creates a new DB object representing a connection to a DB.
|
Modifier and Type | Method and Description |
---|---|
void |
addBatch(PreparedStatement ps,
Object... params)
Adds a batch statement using given
java.sql.PreparedStatement and parameters. |
List<Map> |
all(String query)
Alias to
findAll(String) |
List<Map> |
all(String query,
Object... params)
Alias to
findAll(String, Object...) |
void |
attach(Connection connection)
Attaches a database connection to current thread under a name provided to constructor.
|
void |
close()
Closes connection and detaches it from current thread.
|
void |
close(boolean suppressWarning)
Closes connection and detaches it from current thread.
|
static void |
closeAllConnections()
Closes all current connections.
|
void |
closePreparedStatement(PreparedStatement ps)
Quietly closes the
java.sql.PreparedStatement used in a batch execution. |
void |
commitTransaction()
Commits local transaction.
|
Connection |
connection()
Provides connection from current thread.
|
static Map<String,Connection> |
connections()
Provides connections available on current thread.
|
Long |
count(String table)
Returns count of rows in table.
|
Long |
count(String table,
String query,
Object... params)
Runs a count query, returns a number of matching records.
|
Connection |
detach()
Detaches a connection from current thread and returns an instance of it.
|
int |
exec(String query)
Executes DML.
|
int |
exec(String query,
Object... params)
Executes parametrized DML - will contain question marks as placeholders.
|
int[] |
executeBatch(PreparedStatement ps)
Executes a batch on
java.sql.PreparedStatement . |
RowProcessor |
find(String query,
Object... params)
Executes a raw query and returns an instance of
RowProcessor . |
void |
find(String sql,
RowListener listener)
Executes a raw query and calls instance of
RowListener with every row found. |
List<Map> |
findAll(String query)
This method returns entire resultset as one list.
|
List<Map> |
findAll(String query,
Object... params)
This method returns entire resultset as one list.
|
Object |
firstCell(String query,
Object... params)
This method returns the value of the first column of the first row.
|
List |
firstColumn(String query,
Object... params)
This method returns entire resultset with one column as a list.
|
Connection |
getConnection()
Synonym of
connection() for people who like getters. |
static List<String> |
getCurrrentConnectionNames()
Provides a names' list of current connections.
|
boolean |
hasConnection()
Use to check if there is a connection present on current thread.
|
String |
name()
Return logical name for a database.
|
DB |
open()
This method will open a connection defined in the file 'database.properties' located at
root of classpath.
|
DB |
open(ConnectionSpec spec)
This method is used internally by the framework.
|
DB |
open(DataSource datasource)
Opens a connection from a datasource.
|
DB |
open(String jndiName)
Opens a connection from JNDI based on a registered name.
|
DB |
open(String jndiName,
Properties jndiProperties)
Opens a new connection from JNDI data source by name using explicit JNDI properties.
|
DB |
open(String driver,
String url,
Properties props)
Opens a new connection in case additional driver-specific parameters need to be passed in.
|
DB |
open(String driver,
String url,
String user,
String password)
Opens a new connection based on JDBC properties and attaches it to a current thread.
|
void |
openTransaction()
Opens local transaction.
|
void |
rollbackTransaction()
Rolls back local transaction.
|
PreparedStatement |
startBatch(String parametrizedStatement)
Creates a
java.sql.PreparedStatement to be used in batch executions later. |
<T> T |
withDb(DataSource dataSource,
Supplier<T> supplier)
Convenience method to be used outside ActiveWeb.
|
<T> T |
withDb(String jndiName,
Properties jndiProperties,
Supplier<T> supplier)
Convenience method to be used outside ActiveWeb.
|
<T> T |
withDb(String driver,
String url,
Properties properties,
Supplier<T> supplier)
Convenience method to be used outside ActiveWeb.
|
<T> T |
withDb(String driver,
String url,
String user,
String password,
Supplier<T> supplier)
Convenience method to be used outside ActiveWeb.
|
<T> T |
withDb(String jndiName,
Supplier<T> supplier)
Convenience method to be used outside ActiveWeb.
|
<T> T |
withDb(Supplier<T> supplier)
Convenience method to be used outside ActiveWeb.
|
public static final String DEFAULT_NAME
public DB(String name)
name
- logical name for a database.public DB()
new DB(DB.DEFAULT_NAME)
.public String name()
public DB open(String driver, String url, String user, String password)
driver
- class name of driverurl
- URL connection to DBuser
- user name.password
- password.public DB open(String driver, String url, Properties props)
driver
- driver class nameurl
- JDBC URLprops
- connection propertiespublic DB open(String jndiName)
jndi.properties
file with proper JNDI configuration in it.jndiName
- name of a configured data source.public DB open()
ACTIVE_ENV
environment variable or active_env
system property.
If this variable is not defined, it defaults to 'development' environment.
If there is JUnit on classpath, this method assumes it is running under test, and defaults to 'test'.Configuration.getEnvironment()
public void attach(Connection connection)
connection
- instance of connection to attach to current thread.public Connection detach()
public DB open(DataSource datasource)
datasource
- datasource will be used to acquire a connection.public DB open(String jndiName, Properties jndiProperties)
jndi.properties
cannot be easily updated.jndiName
- name of JNDI data source.jndiProperties
- JNDI propertiespublic DB open(ConnectionSpec spec)
spec
- specification for a JDBC connection.public void close()
close
in interface Closeable
close
in interface AutoCloseable
public void close(boolean suppressWarning)
suppressWarning
- true to not display a warning in case of a problem (connection not there)public Long count(String table)
table
- name of table.public Long count(String table, String query, Object... params)
table
- table in which to count rows.query
- this is a filtering query for the count. If '*' provided, all records will be counted. Example:
"age > 65 AND department = 'accounting'"
params
- parameters for placeholder substitution.public Object firstCell(String query, Object... params)
query
- queryparams
- parameterspublic List<Map> all(String query, Object... params)
findAll(String, Object...)
public List<Map> findAll(String query, Object... params)
List<Map<String, Object>> people = Base.findAll("select * from people where first_name = ?", "John");
for(Map person: people)
System.out.println(person.get("first_name"));
query
- raw SQL query. This query is parametrized.params
- list of parameters for a parametrized query.public List firstColumn(String query, Object... params)
List ssns = Base.firstColumn("select ssn from people where first_name = ?", "John"); for(Object ssn: ssns) System.out.println(ssn);This method collects the value of the first column of each row. If query results have more than one column, the remainder will be ignored.
query
- raw SQL query. This query can be parametrized.params
- list of parameters for a parametrized query.public List<Map> all(String query)
findAll(String)
public List<Map> findAll(String query)
query
- raw SQL query. This query is not parametrized.public RowProcessor find(String query, Object... params)
RowProcessor
. Use it in the following pattern:
Base.find("select first_name, last_name from really_large_table").with(new RowListenerAdapter() { public void onNext(Map row) { ///write your code here Object o1 = row.get("first_name"); Object o2 = row.get("last_name"); } });
query
- raw SQL.params
- list of parameters if query is parametrized.RowProcessor
which has with() method for convenience.public void find(String sql, RowListener listener)
RowListener
with every row found.
Use this method for very large result sets.sql
- raw SQL query.listener
- client listener implementation for processing individual rows.public int exec(String query)
query
- raw DML.public int exec(String query, Object... params)
query
- query to execute - will contain question marks as placeholders.params
- query parameters.public void openTransaction()
public void commitTransaction()
public void rollbackTransaction()
public Connection connection()
public boolean hasConnection()
public Connection getConnection()
connection()
for people who like getters.public static List<String> getCurrrentConnectionNames()
public static void closeAllConnections()
public static Map<String,Connection> connections()
public PreparedStatement startBatch(String parametrizedStatement)
java.sql.PreparedStatement
to be used in batch executions later.parametrizedStatement
- Example of a statement: INSERT INTO employees VALUES (?, ?)
.java.sql.PreparedStatement
with compiled query.public void addBatch(PreparedStatement ps, Object... params)
java.sql.PreparedStatement
and parameters.ps
- java.sql.PreparedStatement
to add batch to.params
- parameters for the query in java.sql.PreparedStatement
. Parameters will be
set on the statement in the same order as provided here.public int[] executeBatch(PreparedStatement ps)
java.sql.PreparedStatement
.ps
- java.sql.PreparedStatement
to execute batch on.public void closePreparedStatement(PreparedStatement ps)
java.sql.PreparedStatement
used in a batch execution. The advantage over calling
java.sql.PreparedStatement.close()
directly is not having to explicitly handle a checked exception
(java.sql.SQLException
).
This method should typically be called in a finally block. So as not to displace any exception (e.g. from a failed
batch execution) that might already be in flight, this method swallows any exception that might arise from
closing the statement. This is generally seen as a worthwhile trade-off, as it much less likely for a close to fail
without a prior failure.ps
- java.sql.PreparedStatement
with which a batch has been executed. If null, this is a no-op.public <T> T withDb(String jndiName, Properties jndiProperties, Supplier<T> supplier)
Runnable
and then will close the connection. The connection to open is the same as in open(String, Properties)
method.
Example of usage:
Object result = withDb("jndiName1", props, () -> { //place code here return res; });
jndiName
- name of a configured data source.jndiProperties
- JNDI properties.supplier
- instance of Supplier
to execute.public <T> T withDb(DataSource dataSource, Supplier<T> supplier)
Runnable
and then will close the connection. The connection to open is the same as in open(DataSource)
method.
Example of usage:
Object result = withDb(datasource, () -> { //place code here return res; });
dataSource
- instance of DataSource
to get a connection from.supplier
- instance of Supplier
to execute.public <T> T withDb(String jndiName, Supplier<T> supplier)
Supplier
and then will close the connection. The connection to open is the same as in open(String)
method.
Example of usage:
Object result = withDb(jndiName, () -> { //place code here return res; });
jndiName
- name of a JNDI connection from containersupplier
- instance of Supplier
to execute.public <T> T withDb(String driver, String url, Properties properties, Supplier<T> supplier)
Supplier
and then will close the connection. The connection to open is the same as in open(String, String, Properties)
method.
Example of usage:
Object results = withDb(driver, url, properties, () -> { //place code here return res; });The arguments to this method are the same as to
open(String, String, Properties)
method.supplier
- instance of Supplier
to execute.public <T> T withDb(String driver, String url, String user, String password, Supplier<T> supplier)
Supplier.get()
and then will close the connection. The connection to open is the same as in
open(String, String, String, String)
method.
Example of usage:
Object result = withDb(driver, url, user, password, () -> { //place code here return val; });The arguments to this method are the same as to
open(String, String, String, String)
method.supplier
- instance of Supplier
to execute.public <T> T withDb(Supplier<T> supplier)
Supplier.get()
and then will close the connection. The connection to open is the same as in open()
method.
Example of usage:
Object result = withDb(() -> { //place code here return res; // whatever it is });
supplier
- instance of Supplier
to execute.Copyright © 2019 JavaLite. All rights reserved.