Package org.javalite.activejdbc
Class Base
- java.lang.Object
-
- org.javalite.activejdbc.Base
-
public class Base extends Object
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 fromDBsuch that in this class you a logical name for a connection is hard-coded to be "default". Use this class when you have only one database. This class is a convenience wrapper ofDB- Author:
- Igor Polevoy, Eric Nielsen
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidaddBatch(PreparedStatement ps, Object... parameters)Adds a batch statement using givenjava.sql.PreparedStatementand parameters.static voidattach(Connection connection)Attaches a database connection to current thread under a default name.static voidclose()Closes connection and detaches it from current thread.static voidclose(boolean suppressWarning)Closes connection and detaches it from current thread.static voidclosePreparedStatement(PreparedStatement ps)Quietly closes thejava.sql.PreparedStatementused in a batch execution.static voidcommitTransaction()Commits local transaction.static Connectionconnection()Returns connection attached to a current thread and named "default".static Longcount(String table)Returns count of rows in table.static Longcount(String table, String query, Object... params)Runs a count query, returns a number of matching records.static Connectiondetach()Detaches a default connection from current thread and returns an instance of it.static intexec(String query)Executes DML.static intexec(String query, Object... params)Executes parametrized DML - will contain question marks as placeholders.static int[]executeBatch(PreparedStatement ps)Executes a batch onjava.sql.PreparedStatement.static RowProcessorfind(String query, Object... params)Executes a raw query and returns an instance ofRowProcessor.static voidfind(String sql, RowListener listener)Executes a raw query and calls instance ofRowListenerwith every row found.static RowProcessorfind(RowProcessor.ResultSetType type, RowProcessor.ResultSetConcur concur, int fetchSize, String query, Object... params)Executes a raw query and returns an instance ofRowProcessor.static List<Map>findAll(String query)This method returns entire resultset as one list.static List<Map>findAll(String query, Object... params)This method returns entire resultset as one list.static ObjectfirstCell(String query, Object... params)Returns a value of the first column of the first row.static ListfirstColumn(String query, Object... params)This method returns entire resultset as one list.static booleanhasConnection()Use to check if there is a default connection present on current thread.static DBopen()This method will open a connection defined in the file 'database.properties' set by an initial previous call toDBConfiguration.loadConfiguration(String).static DBopen(String jndiName)Opens a connection from JNDI based on a registered name.static DBopen(String driver, String url, String user, String password)Opens a new connection based on JDBC properties and attaches it to a current thread.static DBopen(String driver, String url, Properties props)Opens a new connection in case additional driver-specific parameters need to be passed in.static DBopen(String jndiName, Properties jndiProperties)Opens a new connection from JNDI data source by name using explicit JNDI properties.static DBopen(DataSource dataSource)Opens a connection from a datasource.static voidopenTransaction()Opens local transaction.static voidrollbackTransaction()Rolls back local transaction.static PreparedStatementstartBatch(String parametrizedStatement)Creates ajava.sql.PreparedStatementto be used in batch executions later.static <T> TwithDb(String driver, String url, String user, String password, Supplier<T> supplier)Same asDB.withDb(String, String, String, String, Supplier), but with db nameDB.DEFAULT_NAME.static <T> TwithDb(String driver, String url, Properties properties, Supplier<T> supplier)Same asDB.withDb(String, Properties, Supplier), but with db nameDB.DEFAULT_NAME.static <T> TwithDb(String jndiName, Supplier<T> supplier)Same asDB.withDb(String, Supplier), but with db nameDB.DEFAULT_NAME.static <T> TwithDb(String jndiName, Properties jndiProperties, Supplier<T> supplier)Same asDB.withDb(String, Properties, Supplier), but with db nameDB.DEFAULT_NAME.static <T> TwithDb(Supplier<T> supplier)Same asDB.withDb(Supplier), but with db nameDB.DEFAULT_NAME.static <T> TwithDb(DataSource dataSource, Supplier<T> supplier)Same asDB.withDb(DataSource, Supplier), but with db nameDB.DEFAULT_NAME.
-
-
-
Method Detail
-
open
public static 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. If there is JUnit on classpath, this method assumes it is running under test, and defaults to 'test'.
-
open
public static 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 static 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 static 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 static 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 modified.- Parameters:
jndiName- name of JNDI data source.jndiProperties- JNDI properties
-
open
public static 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.
-
connection
public static Connection connection()
Returns connection attached to a current thread and named "default".- Returns:
- connection attached to a current thread and named "default".
-
hasConnection
public static boolean hasConnection()
Use to check if there is a default connection present on current thread.- Returns:
- true if finds default connection on current thread, false if not.
-
close
public static 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)
-
close
public static void close()
Closes connection and detaches it from current thread.
-
count
public static Long count(String table)
Returns count of rows in table.- Parameters:
table- name of table.- Returns:
- count of rows in table.
-
count
public static 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:
- copunt number of records found in a table.
-
firstCell
public static Object firstCell(String query, Object... params)
Returns a value of the first column of the first row. This query expects only one column selected in the select statement. If more than one column returned, it will throwIllegalArgumentException.- Parameters:
query- queryparams- parameters- Returns:
- fetched value, or null if query did not fetch anything.
-
findAll
public static 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> 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 static List firstColumn(String query, Object... params)
This method returns entire resultset as one list. Do not use it for large result sets. Example:List ssns = Base.firstColumn("select ssn from people where first_name = ?", "John"); for(Object ssn: ssns) System.out.println(ssn);This methods expects a query which selects only one column from a table/view. It will throw an exception if more than one columns are fetched in a result set.- 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.
-
findAll
public static 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 static RowProcessor find(String query, Object... params)
Executes a raw query and returns an instance ofRowProcessor. 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"); } });- Parameters:
query- raw SQL.params- list of parameters if query is parametrized.- Returns:
- instance of
RowProcessorwhich has with() method for convenience.
-
find
public static 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: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"); } });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 static 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 static 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 static 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 static void openTransaction()
Opens local transaction.
-
commitTransaction
public static void commitTransaction()
Commits local transaction.
-
rollbackTransaction
public static void rollbackTransaction()
Rolls back local transaction.
-
startBatch
public static 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 static void addBatch(PreparedStatement ps, Object... parameters)
Adds a batch statement using givenjava.sql.PreparedStatementand parameters.- Parameters:
ps-java.sql.PreparedStatementto add batch to.parameters- parameters for the query injava.sql.PreparedStatement. Parameters will be set on the statement in the same order as provided here.
-
executeBatch
public static 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 static 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.
-
attach
public static void attach(Connection connection)
Attaches a database connection to current thread under a default name.- Parameters:
connection- instance of connection to attach to current thread.
-
detach
public static Connection detach()
Detaches a default 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 default connection detached from current thread by name passed to constructor.
-
withDb
public static <T> T withDb(String jndiName, Properties jndiProperties, Supplier<T> supplier)
Same asDB.withDb(String, Properties, Supplier), but with db nameDB.DEFAULT_NAME.
-
withDb
public static <T> T withDb(DataSource dataSource, Supplier<T> supplier)
Same asDB.withDb(DataSource, Supplier), but with db nameDB.DEFAULT_NAME.
-
withDb
public static <T> T withDb(String jndiName, Supplier<T> supplier)
Same asDB.withDb(String, Supplier), but with db nameDB.DEFAULT_NAME.
-
withDb
public static <T> T withDb(String driver, String url, Properties properties, Supplier<T> supplier)
Same asDB.withDb(String, Properties, Supplier), but with db nameDB.DEFAULT_NAME.
-
withDb
public static <T> T withDb(String driver, String url, String user, String password, Supplier<T> supplier)
Same asDB.withDb(String, String, String, String, Supplier), but with db nameDB.DEFAULT_NAME.
-
withDb
public static <T> T withDb(Supplier<T> supplier)
Same asDB.withDb(Supplier), but with db nameDB.DEFAULT_NAME.
-
-