Class SSessionJdbc
- Direct Known Subclasses:
PersistenceSession
SSessionJdbc.open creates a new session and associates it with the current thread.
All transactions must start with a begin()
, which normally creates a new DataSet to store records in. They
with either a commit()
or a rollback()
which normally destroy the DataSet and all records in it.
commit
also flush()
es any outsanding changes.
Methods are then provided to retrieve recrods from the databse by primary key or general query.
There are also convenience method for performing raw SQL queries should that be required.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected void
void
Re-attacheds a detached connection to the current thread.void
begin()
Start a new transaction.void
Begin a new transaction based on a previously detached data setvoid
close()
Main method for closing a session.void
commit()
Flush and purge the transaction cache to the database, and then commit the transaction.<RI extends SRecordInstance>
RIcreate
(SRecordMeta<RI> rmeta, Object... keys) Create a new record.<RI extends SRecordInstance>
RIcreateWithGeneratedKey
(SRecordMeta<RI> rmeta) Creates a new object with a newly generated key.Enables the SimpleORM connection to be disassociated with the current thread, and then possibly attached to another thread.void
dirtyPurge
(SRecordInstance rinst) Removes this record from the cache but without flushing it.protected void
<RI extends SRecordInstance>
RIfind
(SRecordMeta<RI> rmeta, Object... keys) <RI extends SRecordInstance>
RIfind
(SRecordMeta<RI> rmeta, SQueryMode queryMode, Object... keys) Same as findOrCreate but if not existing returns null rather than creating a new record.<RI extends SRecordInstance>
RIfindOrCreate
(SRecordMeta<RI> rmeta, Object... keys) <RI extends SRecordInstance>
RIfindOrCreate
(SRecordMeta<RI> rmeta, SFieldScalar[] selectList, SQueryMode queryMode, Object... keys) Find a record or create one if it does not already exist.<RI extends SRecordInstance>
RIfindOrCreate
(SRecordMeta<RI> rmeta, SQueryMode queryMode, Object... keys) <RI extends SRecordInstance>
RIfindOrCreate
(SRecordMeta<RI> rmeta, SSelectMode selectMode, Object... keys) <RI extends SRecordInstance>
RIfindOrCreate
(SRecordMeta<RI> rmeta, SSelectMode selectMode, SQueryMode queryMode, Object... keys) void
flush()
Flush all records of tables in this transaction to the database.void
flush
(SRecordInstance instance) Flush this instance to the database.void
Flushes and Purges all record instances.void
Flushes this record instance to the database, removes it from the transaction cache, and then destroys the record so that it can no longer be used.Eg.static SSessionJdbc
Retrieve or create the SSession associated with this "Context".boolean
hasBegun()
Transaction is active between begin and commit.protected void
innerOpen
(DataSource source, String connectionName, SDriver driver) Allows SSession to be subclassed.<RI extends SRecordInstance>
RImustFind
(SRecordMeta<RI> rmeta, Object... keys) <RI extends SRecordInstance>
RImustFind
(SRecordMeta<RI> rmeta, SQueryMode queryMode, Object... keys) static SSessionJdbc
open
(DataSource source, String connectionName) static SSessionJdbc
open
(DataSource source, String connectionName, SDriver driver) Attaches a SimpleORM connection to the current thread based on conf.<RI extends SRecordInstance>
List<RI>Execute the query and return a list of records.<RI extends SRecordInstance>
List<RI>queryNoFlush
(SQuery<RI> qry) Query, but without first flushing the cache, not normally used.<RI extends SRecordInstance>
RIqueryOnlyRecord
(SQuery<RI> qry) Same as query but throws an exception if there is more than one record returned.rawQueryMap
(String sql, boolean flush, Object... params) Returns at most one row, else exception.rawQueryMaps
(String sql, boolean flush, Object... params) Executes sql with parameters, returns a list of Maps of values, one map per row.rawQueryOneMap
(String sql, boolean flush, Object... params) Returns exactly one row, else exception.rawQuerySingle
(String sql, boolean flush, Object... params) Returns a single value of at most one row.int
rawUpdateDB
(String sql, Object... params) Convenience routine for doing bulk updates using raw JDBC.int
rawUpdateDBNoFlush
(String sql, Object... params) void
rollback()
Purges the cache and rolls back the transaction.void
setTransactionIsolation
(int mode) Set the transaction isolation mode.toString()
-
Constructor Details
-
SSessionJdbc
protected SSessionJdbc()No direct creation of Connections.
-
-
Method Details
-
open
Attaches a SimpleORM connection to the current thread based on conf. Opens a JDBC connection.connectionName is a simple name that can be used to identify this connection in log traces etc. Eg. the session ID plus the user name. But keep it short for logging.
The driver is usually determined automatically (if null) based on the conf, but if it is overriden make sure to create a new driver instance for each connection.
See TestUte.java for an example of how to create a trivial DataSource from an old style DriverManager
-
open
-
innerOpen
Allows SSession to be subclassed. connection should normally be null, in which case conf.obtainPrimaryJDBCConnection is used to open it. (rawConnection and sDriverName are deprecated.)We use DataSource rather than just Connection to allow a driver to create a second connection to generate keys etc. But that has never been used, and some old code that potentially supported it has been removed.
-
associateWithThread
protected void associateWithThread() -
dissassociateFromThread
protected void dissassociateFromThread() -
getThreadLocalSession
Retrieve or create the SSession associated with this "Context". Normally this just means (indirectly) call getThreadedConnection which finds the connection associated with this thread.(In extras there is an unsupported EJB.SConnectionEJB class which dispached to getTransactionConnection instead.)
It may or may not be begun. May be used to set properties for the connection, which persist between transactions but not between attach ments.
This is never used within SimpleOrm itself, it is just a convenience method for users.
-
close
public void close()Main method for closing a session.Closes the JDBC connection and then calls
detachWithoutClosing
to detach the SimpleORM connection from the current thread. Should usually be put in a finally clause. No error if already detached or closed so safe in finally clauses. -
detachFromThread
Enables the SimpleORM connection to be disassociated with the current thread, and then possibly attached to another thread. It also enables multiple sessions to be used within the same thread without getting mixed thread exceptions. (But not multiple threads to use the same session concurrently.)Rarely used, normally better to just create a session in the appropriate thread. Both Swing and EJBs can be used without doing this.
Do not not do it unless you really have to.
-
attachToThread
public void attachToThread()Re-attacheds a detached connection to the current thread.- See Also:
-
getDataSource
-
begin
public void begin()Start a new transaction. A JDBC connection must already be attached to this thread, and must not be mid transaction. -
begin
Begin a new transaction based on a previously detached data set -
hasBegun
public boolean hasBegun()Transaction is active between begin and commit. -
commit
public void commit()Flush and purge the transaction cache to the database, and then commit the transaction. Note that this is the only way that a transaction should be committed -- do not use JDBC commit directly. Once committed,begin()
must be used to start the next transaction.Also closes any open SResultSets and SPreparedStatements
-
commitAndDetachDataSet
-
rollback
public void rollback()Purges the cache and rolls back the transaction. Any uncommited updates to the database are also rolled back.Also closes any open SResultSets and SPreparedStatements
-
setTransactionIsolation
public void setTransactionIsolation(int mode) Set the transaction isolation mode. SimpleORM does not normally change the isolation mode, but consider setting it to Connection.TRANSACTION_SERIALIZABLE to achieve greater reliability in many databases.- Parameters:
mode
- as defined by java.sql.Connection.setTransactionIsolation
-
flush
public void flush()Flush all records of tables in this transaction to the database. -
flush
Flush this instance to the database. Normally called bySSession.flush()
in reponse tocommit
but can also be called expicitly if the update order needs to be modified. This method does nothing unless the record is dirty.- See Also:
-
SSession#flush
-
flushAndPurge
Flushes this record instance to the database, removes it from the transaction cache, and then destroys the record so that it can no longer be used. Any futurefindOrCreate
will requery the data base and produce a new record.This is useful if one wants to do raw JDBC updates on the record, and be guaranteed not to have an inconsistent cache. (Where bulk updates can be used they are several times faster than updates made via the JVM -- see the benchmarks section in the white paper.)
It can also be useful to force a requery of records if optmistic locks are being broken, although care must be taken not to rely on values returned by a outdated query.
- See Also:
-
SSession#flush
-
flushAndPurge
public void flushAndPurge()Flushes and Purges all record instances. Can be used before a raw JDBC update to ensure that the cache remains consistent after the query.- See Also:
-
SRecordInstance#flushAndPurge
SRecordMeta#flushAndPurge
-
toString
-
queryNoFlush
Query, but without first flushing the cache, not normally used.- See Also:
-
query
Execute the query and return a list of records. First always flushes any dirty records to the database. (Flush but not commit.) -
queryOnlyRecord
Same as query but throws an exception if there is more than one record returned. -
findOrCreate
public <RI extends SRecordInstance> RI findOrCreate(SRecordMeta<RI> rmeta, SFieldScalar[] selectList, SQueryMode queryMode, Object... keys) Find a record or create one if it does not already exist. Retrieve selectList fields, use queryMode.- Specified by:
findOrCreate
in classSSessionI
-
findOrCreate
public <RI extends SRecordInstance> RI findOrCreate(SRecordMeta<RI> rmeta, SSelectMode selectMode, SQueryMode queryMode, Object... keys) -
findOrCreate
public <RI extends SRecordInstance> RI findOrCreate(SRecordMeta<RI> rmeta, SSelectMode selectMode, Object... keys) -
findOrCreate
public <RI extends SRecordInstance> RI findOrCreate(SRecordMeta<RI> rmeta, SQueryMode queryMode, Object... keys) -
findOrCreate
-
mustFind
public <RI extends SRecordInstance> RI mustFind(SRecordMeta<RI> rmeta, SQueryMode queryMode, Object... keys) -
mustFind
-
find
public <RI extends SRecordInstance> RI find(SRecordMeta<RI> rmeta, SQueryMode queryMode, Object... keys) Same as findOrCreate but if not existing returns null rather than creating a new record. (Note that it may still need to query the database to determine if it is not there.) -
find
-
create
Create a new record.Assumes the record is new, will do an insert at flush time which will cause a unique index violation if it was not. Use a findOrCreate followed by assertNewRow if it is unclear whether the row is really new.
-
createWithGeneratedKey
Creates a new object with a newly generated key. Note that the SELECT MAX method is used unless a database dependent alternative is available (currently only for PostgreSQL).SGENERATED_KEY
.Always creates a new empty record. ## This code is partially copied into SRecordInstance.attach() for records created while detached.
-
dirtyPurge
Removes this record from the cache but without flushing it. Any changes to it will be lost. This might be useful if the record is being manually updated/deleted and you want to deliberately ignore any direct changes.Dangerous, use with care.
-
rawUpdateDB
Convenience routine for doing bulk updates using raw JDBC. Dangerous. Take care with caching and never use this to commit a transaction. Returns number of rows updated. Does nothing if sql == null.Flushes before performing update. But does not requery any updated records.
-
rawUpdateDBNoFlush
-
rawQueryMaps
Executes sql with parameters, returns a list of Maps of values, one map per row. The key to the maps is the meta data returned by JDBC. This is normally just the column name, but can be specified in most SQLs. eg.SELECT MAX(SALARY) AS MAX_SAL ... FROM ....
-
rawQueryMap
Returns at most one row, else exception. Null if none. -
rawQueryOneMap
Returns exactly one row, else exception. Exception if none. -
rawQuerySingle
Returns a single value of at most one row. -
getLogger
-
getJdbcConnection
-
getDataSet
-
getDriver
Eg. if (getDriver() instanceOf SDriverPostgres) ... Also getDriver().setMyFavoritePerConnectionParameter. -
getStatistics
-