Class 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_COUNT SingleOutcome, etc.

    Methods insert(Outcome), update(Outcome), execute(), and select(Outcome) clean the list of arguments pre-set by set(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) (with false as 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 Connection instance, 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 call autocommit(boolean) with false as 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) with false as 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 Detail

      • JdbcSession

        public JdbcSession​(DataSource src)
        Public ctor.

        If all you have is a Connection, wrap it inside our StaticSource, 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
      • 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 to String using their toString() 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
      • insert

        public <T> T insert​(Outcome<T> outcome)
                     throws SQLException
        Make SQL INSERT request.

        Outcome will receive a ResultSet of 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 SQL UPDATE request.

        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 SQL SELECT request.

        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