Class JdbcSession
- java.lang.Object
-
- com.jcabi.jdbc.JdbcSession
-
public final class JdbcSession extends Object
Universal JDBC wrapper.Execute a simple SQL query over a JDBC data source:
String name = new JdbcSession(source) .sql("SELECT name FROM foo WHERE id = ?") .set(123) .select( new Outcome<String>() { @Override public String handle(final ResultSet rset) throws SQLException { rset.next(); return rset.getString(1); } } );There are a number of convenient pre-defined outcomes, like
Outcome.VOID,Outcome.NOT_EMPTY,Outcome.UPDATE_COUNTSingleOutcome, etc.Methods
insert(Outcome),update(Outcome),execute(), andselect(Outcome)clean the list of arguments pre-set byset(Object). The class can be used for a complex transaction, when it's necessary to perform a number of SQL statements in a group. For example, the following construct will execute two SQL queries, in a single transaction and will "commit" at the end (or rollback the entire transaction in case of any error in between):new JdbcSession(source) .autocommit(false) .sql("START TRANSACTION") .execute() .sql("DELETE FROM foo WHERE id = ?") .set(444) .execute() .set(555) .execute() .commit();The following SQL queries will be sent to the database:
START TRANSACTION; DELETE FROM foo WHERE id = 444; DELETE FROM foo WHERE id = 555; COMMIT;
autocommit(boolean)(withfalseas an argument) can be used when it's necessary to execute a statement and leave the connection open. For example when shutting down the database through SQL:new JdbcSession(/* H2 Database data source */) .autocommit(false) .sql("SHUTDOWN COMPACT") .execute();IMPORTANT:
If you rely on one specific
Connectioninstance, be careful if you are using it in more places, especially if more references of this class use it - one of those references might close the connection if you forget to callautocommit(boolean)withfalseas an argument, for example:Connection connection = [...]; DataSource ds = new StaticSource(connection); new JdbcSession(ds) .sql("SQL STATEMENT") .execute(); new JdbcSession(ds) .sql("SQL STATEMENT 2") .execute();The above example will fail because the first JdbcSession closes the connection, and the next one tries to work with it closed. In order to not have this failure, the first session has to call
autocommit(boolean)withfalseas an argument, like this:Connection connection = [...]; DataSource ds = new StaticSource(connection); new JdbcSession(ds) .autocommit(false) .sql("SQL STATEMENT") .execute(); new JdbcSession(ds) .sql("SQL STATEMENT 2") .execute();This class is thread-safe.
- Since:
- 0.1.8
-
-
Constructor Summary
Constructors Constructor Description JdbcSession(DataSource src)Public ctor.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description JdbcSessionautocommit(boolean autocommit)Shall we auto-commit?<T> Tcall(Outcome<T> outcome)Call an SQL stored procedure.JdbcSessionclear()Clear all pre-set parameters (args, preparations, etc).voidcommit()Commit the transaction (callsConnection.commit()and thenConnection.close()).JdbcSessionexecute()Make SQL request expecting no response from the server.<T> Tinsert(Outcome<T> outcome)Make SQLINSERTrequest.JdbcSessionprepare(Preparation prp)Run this preparation before executing the statement.voidrollback()Rollback the transaction (callsConnection.rollback()and thenConnection.close()).<T> Tselect(Outcome<T> outcome)Make SQLSELECTrequest.JdbcSessionset(Object value)Set new parameter for the query.JdbcSessionsql(String sql)Use this SQL query (with optional parameters inside).<T> Tupdate(Outcome<T> outcome)Make SQLUPDATErequest.
-
-
-
Constructor Detail
-
JdbcSession
public JdbcSession(DataSource src)
Public ctor.If all you have is a
Connection, wrap it inside ourStaticSource, but make sure you understand the autocommit mechanism we have in place here. Read the class' javadoc (especially the last paragraph, marked with IMPORTANT).- Parameters:
src- Data source
-
-
Method Detail
-
sql
public JdbcSession sql(String sql)
Use this SQL query (with optional parameters inside).The query will be used in
PreparedStatement, that's why you can use the same formatting as there. Arguments shall be marked as"?"(question marks). For example:String name = new JdbcSession(source) .sql("INSERT INTO foo (id, name) VALUES (?, ?)") .set(556677) .set("Jeffrey Lebowski") .insert(Outcome.VOID);- Parameters:
sql- The SQL query to use- Returns:
- This object
-
autocommit
public JdbcSession autocommit(boolean autocommit)
Shall we auto-commit?By default this flag is set to TRUE, which means that methods
insert(Outcome),execute(), andselect(Outcome)will callConnection.commit()after their successful execution.- Parameters:
autocommit- Shall we?- Returns:
- This object
-
set
public JdbcSession set(Object value)
Set new parameter for the query.The following types are supported:
Boolean,Date,Utc,Long,Float, byte[],Integer,UUID. All other types will be converted toStringusing theirtoString()methods.- Parameters:
value- The value to add- Returns:
- This object
-
prepare
public JdbcSession prepare(Preparation prp)
Run this preparation before executing the statement.- Parameters:
prp- Preparation- Returns:
- This object
- Since:
- 0.13
-
clear
public JdbcSession clear()
Clear all pre-set parameters (args, preparations, etc).- Returns:
- This object
- Since:
- 0.13
-
commit
public void commit() throws SQLExceptionCommit the transaction (callsConnection.commit()and thenConnection.close()).- Throws:
SQLException- If fails to do the SQL operation
-
rollback
public void rollback() throws SQLExceptionRollback the transaction (callsConnection.rollback()and thenConnection.close()).- Throws:
SQLException- If fails to do the SQL operation
-
insert
public <T> T insert(Outcome<T> outcome) throws SQLException
Make SQLINSERTrequest.Outcomewill receive aResultSetof generated keys.JDBC connection is opened and, optionally, closed by this method.
- Type Parameters:
T- Type of response- Parameters:
outcome- The outcome of the operation- Returns:
- The result
- Throws:
SQLException- If fails
-
update
public <T> T update(Outcome<T> outcome) throws SQLException
Make SQLUPDATErequest.JDBC connection is opened and, optionally, closed by this method.
- Type Parameters:
T- Type of result expected- Parameters:
outcome- Outcome of the operation- Returns:
- This object
- Throws:
SQLException- If fails
-
call
public <T> T call(Outcome<T> outcome) throws SQLException
Call an SQL stored procedure.JDBC connection is opened and, optionally, committed by this method, depending on the autocommit class attribute: if it's value is true, the connection will be committed after this call.
- Type Parameters:
T- Type of result expected- Parameters:
outcome- Outcome of the operation- Returns:
- Result of type T
- Throws:
SQLException- If fails
-
execute
public JdbcSession execute() throws SQLException
Make SQL request expecting no response from the server.This method should be used for schema manipulation statements, like CREATE TABLE, CREATE INDEX, DROP COLUMN, etc. and server-side instructions that return no data back. Main difference between this one and
#execute()is that the later requests JDBC to return generated keys. When SQL server doesn't return any keys this may cause runtime exceptions in JDBC.JDBC connection is opened and, optionally, closed by this method.
- Returns:
- This object
- Throws:
SQLException- If fails- Since:
- 0.9
-
select
public <T> T select(Outcome<T> outcome) throws SQLException
Make SQLSELECTrequest.JDBC connection is opened and, optionally, closed by this method.
- Type Parameters:
T- Type of response- Parameters:
outcome- The outcome of the operation- Returns:
- The result
- Throws:
SQLException- If fails
-
-