Package org.javalite.activejdbc
Class DB
- java.lang.Object
-
- org.javalite.activejdbc.DB
-
- All Implemented Interfaces:
Closeable,AutoCloseable
public class DB extends Object implements Closeable
This class provides a number of convenience methods for opening/closing database connections, running various types of queries, and executing SQL statements. This class differs fromBasesuch 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.- Author:
- Igor Polevoy, Eric Nielsen
-
-
Field Summary
Fields Modifier and Type Field Description static StringDEFAULT_NAME
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddBatch(PreparedStatement ps, Object... params)Adds a batch statement using givenjava.sql.PreparedStatementand parameters.List<Map>all(String query)Alias tofindAll(String)List<Map>all(String query, Object... params)Alias tofindAll(String, Object...)voidattach(Connection connection)Attaches a database connection to current thread under a name provided to constructor.voidclose()Closes connection and detaches it from current thread.voidclose(boolean suppressWarning)Closes connection and detaches it from current thread.static voidcloseAllConnections()Closes all current connections.voidclosePreparedStatement(PreparedStatement ps)Quietly closes thejava.sql.PreparedStatementused in a batch execution.voidcommitTransaction()Commits local transaction.Connectionconnection()Provides connection from current thread.static Map<String,Connection>connections()Provides connections available on current thread.Longcount(String table)Returns count of rows in table.Longcount(String table, String query, Object... params)Runs a count query, returns a number of matching records.Connectiondetach()Detaches a connection from current thread and returns an instance of it.intexec(String query)Executes DML.intexec(String query, Object... params)Executes parametrized DML - will contain question marks as placeholders.int[]executeBatch(PreparedStatement ps)Executes a batch onjava.sql.PreparedStatement.RowProcessorfind(String query, Object... params)Convenience method, same asfind(RowProcessor.ResultSetType, RowProcessor.ResultSetConcur, int, String, Object...), but passes in default values:voidfind(String sql, RowListener listener)Executes a raw query and calls instance ofRowListenerwith every row found.RowProcessorfind(RowProcessor.ResultSetType type, RowProcessor.ResultSetConcur concur, int fetchSize, String query, Object... params)Executes a raw query and returns an instance ofRowProcessor.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.ObjectfirstCell(String query, Object... params)This method returns the value of the first column of the first row.ListfirstColumn(String query, Object... params)This method returns entire resultset with one column as a list.ConnectiongetConnection()Synonym ofconnection()for people who like getters.static List<String>getCurrrentConnectionNames()Provides a names' list of current connections.booleanhasConnection()Use to check if there is a connection present on current thread.Stringname()Return logical name for a database.DBopen()This method will open a connection defined in the file 'database.properties' set by an initial previous call toDBConfiguration.loadConfiguration(String).DBopen(String jndiName)Opens a connection from JNDI based on a registered name.DBopen(String driver, String url, String user, String password)Opens a new connection based on JDBC properties and attaches it to a current thread.DBopen(String driver, String url, Properties props)Opens a new connection in case additional driver-specific parameters need to be passed in.DBopen(String jndiName, Properties jndiProperties)Opens a new connection from JNDI data source by name using explicit JNDI properties.DBopen(DataSource datasource)Opens a connection from a datasource.DBopen(ConnectionConfig config)This method is used internally by the framework.voidopenTransaction()Opens local transaction.voidrollbackTransaction()Rolls back local transaction.PreparedStatementstartBatch(String parametrizedStatement)Creates ajava.sql.PreparedStatementto be used in batch executions later.<T> TwithDb(String driver, String url, String user, String password, Supplier<T> supplier)Convenience method to be used outside ActiveWeb.<T> TwithDb(String driver, String url, Properties properties, Supplier<T> supplier)Convenience method to be used outside ActiveWeb.<T> TwithDb(String jndiName, Supplier<T> supplier)Convenience method to be used outside ActiveWeb.<T> TwithDb(String jndiName, Properties jndiProperties, Supplier<T> supplier)Convenience method to be used outside ActiveWeb.<T> TwithDb(Supplier<T> supplier)Convenience method to be used outside ActiveWeb.<T> TwithDb(DataSource dataSource, Supplier<T> supplier)Convenience method to be used outside ActiveWeb.
-
-
-
Field Detail
-
DEFAULT_NAME
public static final String DEFAULT_NAME
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
DB
public DB(String name)
Creates a new DB object representing a connection to a DB.- Parameters:
name- logical name for a database.
-
DB
public DB()
Creates a new DB object representing a connection to a DB with default name. Calling this constructor is equivalent tonew DB(DB.DEFAULT_NAME).
-
-
Method Detail
-
name
public String name()
Return logical name for a database.- Returns:
- logical name for a database.
-
open
public 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.- Parameters:
driver- class name of driverurl- URL connection to DBuser- user name.password- password.
-
open
public DB open(String driver, String url, Properties props)
Opens a new connection in case additional driver-specific parameters need to be passed in.- Parameters:
driver- driver class nameurl- JDBC URLprops- connection properties
-
open
public DB open(String jndiName)
Opens a connection from JNDI based on a registered name. This assumes that there is ajndi.propertiesfile with proper JNDI configuration in it.- Parameters:
jndiName- name of a configured data source.
-
open
public DB open()
This method will open a connection defined in the file 'database.properties' set by an initial previous call toDBConfiguration.loadConfiguration(String). The connection picked up from the file is defined byACTIVE_ENVenvironment variable oractive_envsystem property. If this variable is not defined, it defaults to 'development' environment. It is expected to find a single connection configuration in a current environment.- See Also:
AppConfig.activeEnv()
-
attach
public void attach(Connection connection)
Attaches a database connection to current thread under a name provided to constructor.- Parameters:
connection- instance of connection to attach to current thread.
-
detach
public Connection detach()
Detaches a connection from current thread and returns an instance of it. This method does not close a connection. Use it for cases of advanced connection management, such as integration with Spring Framework.- Returns:
- instance of a connection detached from current thread by name passed to constructor.
-
open
public DB open(DataSource datasource)
Opens a connection from a datasource. This methods gives a high level control while sourcing a DB connection.- Parameters:
datasource- datasource will be used to acquire a connection.
-
open
public DB open(String jndiName, Properties jndiProperties)
Opens a new connection from JNDI data source by name using explicit JNDI properties. This method can be used in cases when filejndi.propertiescannot be easily updated.- Parameters:
jndiName- name of JNDI data source.jndiProperties- JNDI properties
-
open
public DB open(ConnectionConfig config)
This method is used internally by the framework.- Parameters:
config- specification for a JDBC connection.
-
close
public void close()
Closes connection and detaches it from current thread.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
close
public void close(boolean suppressWarning)
Closes connection and detaches it from current thread.- Parameters:
suppressWarning- true to not display a warning in case of a problem (connection not there)
-
count
public Long count(String table)
Returns count of rows in table.- Parameters:
table- name of table.- Returns:
- count of rows in table.
-
count
public Long count(String table, String query, Object... params)
Runs a count query, returns a number of matching records.- Parameters:
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.- Returns:
- count number of records found in a table.
-
firstCell
public Object firstCell(String query, Object... params)
This method returns the value of the first column of the first row. If query results have more than one column or more than one row, they will be ignored.- Parameters:
query- queryparams- parameters- Returns:
- fetched value, or null if query did not fetch anything.
-
all
public List<Map> all(String query, Object... params)
Alias tofindAll(String, Object...)
-
findAll
public List<Map> findAll(String query, Object... params)
This method returns entire resultset as one list. Do not use it for large result sets. Example: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"));- Parameters:
query- raw SQL query. This query is parametrized.params- list of parameters for a parametrized query.- Returns:
- entire result set corresponding to the query.
-
firstColumn
public List firstColumn(String query, Object... params)
This method returns entire resultset with one column as a list. Do not use it for large result sets. Example:List ssns = new DB("default").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.- Parameters:
query- raw SQL query. This query can be parametrized.params- list of parameters for a parametrized query.- Returns:
- entire result set corresponding to the query.
-
all
public List<Map> all(String query)
Alias tofindAll(String)
-
findAll
public List<Map> findAll(String query)
This method returns entire resultset as one list. Do not use it for large result sets.- Parameters:
query- raw SQL query. This query is not parametrized.- Returns:
- entire result set corresponding to the query.
-
find
public RowProcessor find(String query, Object... params)
Convenience method, same asfind(RowProcessor.ResultSetType, RowProcessor.ResultSetConcur, int, String, Object...), but passes in default values:RowProcessor.ResultSetType.FORWARD_ONLY, RowProcessor.ResultSetConcur.READ_ONLY, 0Executes a raw query and returns an instance ofRowProcessor. Use it in the following pattern:new DB("default").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"); } });- Parameters:
query- raw SQL, parametrized if neededparams- list of parameters if query is parametrized.- Returns:
- instance of
RowProcessorwhich has with() method for convenience.
-
find
public RowProcessor find(RowProcessor.ResultSetType type, RowProcessor.ResultSetConcur concur, int fetchSize, String query, Object... params)
Executes a raw query and returns an instance ofRowProcessor. Use it in the following pattern:new DB("default").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"); } });See ResultSet Docs- Parameters:
query- raw SQL.type- type of result setconcur- concurrent mode of result setfetchSize- size of result setparams- list of parameters if query is parametrized.- Returns:
- instance of
RowProcessorwhich has with() method for convenience.
-
find
public void find(String sql, RowListener listener)
Executes a raw query and calls instance ofRowListenerwith every row found. Use this method for very large result sets.- Parameters:
sql- raw SQL query.listener- client listener implementation for processing individual rows.
-
exec
public int exec(String query)
Executes DML. Use it for inserts and updates.- Parameters:
query- raw DML.- Returns:
- number of rows afected by query.
-
exec
public int exec(String query, Object... params)
Executes parametrized DML - will contain question marks as placeholders.- Parameters:
query- query to execute - will contain question marks as placeholders.params- query parameters.- Returns:
- number of records affected.
-
openTransaction
public void openTransaction()
Opens local transaction.
-
commitTransaction
public void commitTransaction()
Commits local transaction.
-
rollbackTransaction
public void rollbackTransaction()
Rolls back local transaction.
-
connection
public Connection connection()
Provides connection from current thread.- Returns:
- connection from current thread.
-
hasConnection
public boolean hasConnection()
Use to check if there is a connection present on current thread.- Returns:
- true if finds connection on current thread, false if not.
-
getConnection
public Connection getConnection()
Synonym ofconnection()for people who like getters.- Returns:
- connection from current thread.
-
getCurrrentConnectionNames
public static List<String> getCurrrentConnectionNames()
Provides a names' list of current connections.- Returns:
- a names' list of current connections.
-
closeAllConnections
public static void closeAllConnections()
Closes all current connections.
-
connections
public static Map<String,Connection> connections()
Provides connections available on current thread.- Returns:
- connections available on current thread.
-
startBatch
public PreparedStatement startBatch(String parametrizedStatement)
Creates ajava.sql.PreparedStatementto be used in batch executions later.- Parameters:
parametrizedStatement- Example of a statement:INSERT INTO employees VALUES (?, ?).- Returns:
- instance of
java.sql.PreparedStatementwith compiled query.
-
addBatch
public void addBatch(PreparedStatement ps, Object... params)
Adds a batch statement using givenjava.sql.PreparedStatementand parameters.- Parameters:
ps-java.sql.PreparedStatementto add batch to.params- parameters for the query injava.sql.PreparedStatement. Parameters will be set on the statement in the same order as provided here.
-
executeBatch
public int[] executeBatch(PreparedStatement ps)
Executes a batch onjava.sql.PreparedStatement.- Parameters:
ps-java.sql.PreparedStatementto execute batch on.- Returns:
- an array of update counts containing one element for each command in the batch. The elements of the array are ordered according to the order in which commands were added to the batch.
- See Also:
- Statement#executeBatch()
-
closePreparedStatement
public void closePreparedStatement(PreparedStatement ps)
Quietly closes thejava.sql.PreparedStatementused in a batch execution. The advantage over callingjava.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.- Parameters:
ps-java.sql.PreparedStatementwith which a batch has been executed. If null, this is a no-op.
-
withDb
public <T> T withDb(String jndiName, Properties jndiProperties, Supplier<T> supplier)
Convenience method to be used outside ActiveWeb. This method will open a connection, run theRunnableand then will close the connection. The connection to open is the same as inopen(String, Properties)method. Example of usage:Object result = withDb("jndiName1", props, () -> { //place code here return res; });- Parameters:
jndiName- name of a configured data source.jndiProperties- JNDI properties.supplier- instance ofSupplierto execute.
-
withDb
public <T> T withDb(DataSource dataSource, Supplier<T> supplier)
Convenience method to be used outside ActiveWeb. This method will open a connection, run theRunnableand then will close the connection. The connection to open is the same as inopen(DataSource)method. Example of usage:Object result = withDb(datasource, () -> { //place code here return res; });- Parameters:
dataSource- instance ofDataSourceto get a connection from.supplier- instance ofSupplierto execute.
-
withDb
public <T> T withDb(String jndiName, Supplier<T> supplier)
Convenience method to be used outside ActiveWeb. This method will open a connection, run theSupplierand then will close the connection. The connection to open is the same as inopen(String)method. Example of usage:Object result = withDb(jndiName, () -> { //place code here return res; });- Parameters:
jndiName- name of a JNDI connection from containersupplier- instance ofSupplierto execute.
-
withDb
public <T> T withDb(String driver, String url, Properties properties, Supplier<T> supplier)
Convenience method to be used outside ActiveWeb. This method will open a connection, run theSupplierand then will close the connection. The connection to open is the same as inopen(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 toopen(String, String, Properties)method.- Parameters:
supplier- instance ofSupplierto execute.
-
withDb
public <T> T withDb(String driver, String url, String user, String password, Supplier<T> supplier)
Convenience method to be used outside ActiveWeb. This method will open a connection, run theSupplier.get()and then will close the connection. The connection to open is the same as inopen(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 toopen(String, String, String, String)method.- Parameters:
supplier- instance ofSupplierto execute.
-
withDb
public <T> T withDb(Supplier<T> supplier)
Convenience method to be used outside ActiveWeb. This method will open a connection, run theSupplier.get()and then will close the connection. The connection to open is the same as inopen()method. Example of usage:Object result = new DB("events").withDb(() -> { //place code here return res; // whatever it is });- Parameters:
supplier- instance ofSupplierto execute.
-
-