org.ujorm.orm
Class Session

java.lang.Object
  extended by org.ujorm.orm.Session
All Implemented Interfaces:
Closeable

public class Session
extends Object
implements Closeable

The ORM session.
Methods of the session are not thread safe.


Field Summary
static String SQL_ILLEGAL
          Exception SQL message prefix
 
Method Summary
 Transaction beginTransaction()
          Create a new transaction or a sub-transaction.
protected  void call(DbProcedure procedure)
          Call the stored procedure
protected  void checkNotNull(OrmUjo ujo, String action)
          Check the Ujo object to not null.
 void clearCache()
          Clear the cache.
 void clearCache(CachePolicy policy)
          Clear cache and change its policy.
 void close()
          Close and release all DB connections.
 void commit()
          Make a commit for all databases.
 void commit(boolean commit)
          Make commit/rollback for all 'production' databases.
 void commitTransaction()
          Make a commit om all databases for the current transaction level.
protected  Criterion createPkCriterion(OrmUjo bo)
          Returns an criterion by a PrimaryKey
<UJO extends OrmUjo>
Query<UJO>
createQuery(Class<UJO> aClass)
          Create query for all table rows.
<UJO extends OrmUjo>
Query<UJO>
createQuery(Class<UJO> aClass, Criterion<UJO> criterion)
          Deprecated. Use the method createQuery(Criterion, Class) rather.
<UJO extends OrmUjo>
Query<UJO>
createQuery(Criterion<UJO> criterion)
          The table class is derived from the first criterion column.
<UJO extends OrmUjo>
Query<UJO>
createQuery(Criterion<UJO> criterion, Class<UJO> aClass)
          Create query.
<UJO extends OrmUjo>
int
delete(Class<UJO> tableClass, Criterion<UJO> criterion)
          Delete all object object by the criterion from parameter.
<UJO extends OrmUjo>
int
delete(Criterion<UJO> criterion)
          Delete all object object by the criterion from parameter.
protected
<UJO extends OrmUjo>
int
delete(MetaTable tableModel, Criterion<UJO> criterion)
          Delete all objects object form parameter
Warning: method does not remove deleted object from internal cache, however you can call method clearCache() to release all objects from the cache.
 int delete(OrmUjo bo)
          Delete an optional object from the parameters.
<UJO extends OrmUjo>
boolean
exists(Class<UJO> entity)
          Returns true if exists any database row for the required entity.
<UJO extends OrmUjo>
boolean
exists(Criterion<UJO> criterion)
          Returns true if exists any database row with the required condition.
protected
<UJO extends OrmUjo>
boolean
exists(MetaTable table, Criterion<UJO> criterion, Key pk)
          Returns true if exists any database row for the required criterion.
 OrmUjo findCache(Class type, Object... pkeys)
          Find object from internal cache
 OrmUjo findCache(Class type, Object pkey)
          Find object from internal cache
 MetaRelation2Many getBasicColumn(Criterion criterion)
          Returns the first "basic" column of criterion.
 Connection getConnection(int databaseIndex, boolean toModify)
          Get a Connection for a required databse by a database order number (index).
 Connection getConnection(MetaDatabase database, boolean toModify)
          Get or create a Connection for a required database with an autocommit na false.
<DB extends OrmUjo>
DB
getDatabase(Class<DB> dbType)
          Returns a Database instance.
 SqlDialect getDialect(Class<? extends OrmUjo> ormType)
          Check dialecttype
 Connection getFirstConnection()
          Get the first Connection where an autocommit is set to false.
 Connection getFirstConnection(boolean toModify)
          Get the first Connection where an autocommit is set to false.
<DB extends OrmUjo>
DB
getFirstDatabase()
          Returns the first Database instance.
 OrmHandler getHandler()
          Returns a handler
 LazyLoading getLazyLoading()
          Enable a lazy-loading of related Ujo object.
protected  List<MetaColumn> getOrmColumns(Key... keys)
          Convert a key array to a column list.
 MetaParams getParameters()
          Returns parameters
<UJO extends OrmUjo>
long
getRowCount(Query<UJO> query)
          Returns a count of rows
 JdbcStatement getStatement(MetaDatabase database, CharSequence sql, boolean toModify)
          Create new statement and assigng Savepoint for a trnasaction sase.
 JdbcStatement getStatement(Query query)
          Run SQL SELECT by query.
 JdbcStatement getStatementCallable(MetaDatabase database, String sql, boolean toModify)
          Create new statement
 Transaction getTransaction()
          Returns the current transaction
 boolean hasDialect(Class<? extends OrmUjo> ormType, Class<? extends SqlDialect>... dialects)
          Returns true, if Corm type have got any from listed dialects
 boolean isClosed()
          Is the session closed?
 boolean isRollbackOnly()
          The rollback is allowed only.
<UJO extends OrmUjo>
UjoIterator<UJO>
iterateInternal(RelationToMany key, OrmUjo value)
          Iterate key of values
<UJO extends OrmUjo>
UJO
load(Class<UJO> tableType, Object id)
          Load UJO by a unique id.
<UJO extends OrmUjo>
UJO
loadBy(UJO ujo)
          Load UJO by a unique id.
<UJO extends OrmUjo>
UJO
loadInternal(Key relatedProperty, Object id, boolean mandatory)
          Load UJO by a unique id.
 void markForRolback()
           
static Session newClosedSession(OrmHandler handler)
          Create the closed session
 ForeignKey readFK(OrmUjo ujo, Key<?,? extends OrmUjo> key)
          Build new Forign key.
 boolean reload(OrmUjo ujo)
          Reload values of the persistent object.
 void rollback()
          Make a rollback for all databases.
 void rollbackTransaction()
          Make a rollback on all databases for the current transaction level.
 void save(List<? extends OrmUjo> bos)
          INSERT object into table using the Multirow inserts.
 void save(List<? extends OrmUjo> bos, int multiLimit)
          INSERT object into table using the Multirow inserts.
 void save(OrmUjo bo)
          INSERT object into table.
 void saveOrUpdate(OrmUjo bo)
          Make a statement INSERT or UPDATE into a database table according to attribute Session.
 void setLazyLoading(LazyLoading lazyLoadingEnabled)
          Enable a lazy-loading of related Ujo object.
 int update(OrmUjo bo)
          Database UPDATE of the modified columns for the selected object.
 int update(OrmUjo bo, Criterion criterion)
          Database Batch UPDATE of the modified columns along a criterion.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SQL_ILLEGAL

public static final String SQL_ILLEGAL
Exception SQL message prefix

See Also:
Constant Field Values
Method Detail

beginTransaction

public Transaction beginTransaction()
                             throws IllegalStateException
Create a new transaction or a sub-transaction.

Returns:
Create new (sub) transaction
Throws:
IllegalStateException - Throw the Exception if a Transaction is running

getTransaction

public Transaction getTransaction()
Returns the current transaction

Returns:
Return null if no transaction is running.

getHandler

public final OrmHandler getHandler()
Returns a handler


commitTransaction

public void commitTransaction()
Make a commit om all databases for the current transaction level.


commit

public void commit()
Make a commit for all databases.


rollbackTransaction

public void rollbackTransaction()
Make a rollback on all databases for the current transaction level.


rollback

public final void rollback()
Make a rollback for all databases.


commit

public final void commit(boolean commit)
                  throws IllegalStateException
Make commit/rollback for all 'production' databases.

Parameters:
commit - if parameters is false than make a rollback.
Throws:
IllegalStateException

createQuery

public <UJO extends OrmUjo> Query<UJO> createQuery(Class<UJO> aClass)
Create query for all table rows.


createQuery

@Deprecated
public final <UJO extends OrmUjo> Query<UJO> createQuery(Class<UJO> aClass,
                                                                    Criterion<UJO> criterion)
Deprecated. Use the method createQuery(Criterion, Class) rather.

Create query.

See Also:
createQuery(org.ujorm.criterion.Criterion, java.lang.Class), createQuery(org.ujorm.criterion.Criterion)

createQuery

public final <UJO extends OrmUjo> Query<UJO> createQuery(Criterion<UJO> criterion,
                                                         Class<UJO> aClass)
Create query. This method has a slightly higher performance than the method createQuery(Criteron) without the Class parameter.

See Also:
createQuery(org.ujorm.criterion.Criterion)

createQuery

public final <UJO extends OrmUjo> Query<UJO> createQuery(Criterion<UJO> criterion)
The table class is derived from the first criterion column.


exists

public final <UJO extends OrmUjo> boolean exists(Criterion<UJO> criterion)
Returns true if exists any database row with the required condition.


exists

public final <UJO extends OrmUjo> boolean exists(Class<UJO> entity)
Returns true if exists any database row for the required entity.


exists

protected final <UJO extends OrmUjo> boolean exists(MetaTable table,
                                                    Criterion<UJO> criterion,
                                                    Key pk)
Returns true if exists any database row for the required criterion.


getBasicColumn

public MetaRelation2Many getBasicColumn(Criterion criterion)
Returns the first "basic" column of criterion.

Returns:
Not null result

getFirstDatabase

public final <DB extends OrmUjo> DB getFirstDatabase()
Returns the first Database instance.


getDatabase

public <DB extends OrmUjo> DB getDatabase(Class<DB> dbType)
Returns a Database instance. If parameter is null, than method returns the first database.


saveOrUpdate

public void saveOrUpdate(OrmUjo bo)
                  throws IllegalStateException
Make a statement INSERT or UPDATE into a database table according to attribute Session. Related objects must be saved using an another call of the method.

Throws:
IllegalStateException

save

public void save(List<? extends OrmUjo> bos)
          throws IllegalStateException
INSERT object into table using the Multirow inserts.

Parameters:
multiLimit - Row limit for the one insert. If the value will be out of range <1,bos.size()> than the value will be corrected. If the list item count is greather than multi limit so insert will be separated by more multirow inserts.
Throws:
IllegalStateException
See Also:
MetaParams.INSERT_MULTIROW_ITEM_LIMIT

save

public void save(List<? extends OrmUjo> bos,
                 int multiLimit)
          throws IllegalStateException
INSERT object into table using the Multirow inserts.

Parameters:
bos - List of the business object of the same class. If the list must not contain object of different types
multiLimit - Row limit for the one insert. If the value will be out of range <1,bos.size()> than the value will be corrected. If the list item count is greather than multi limit so insert will be separated by more multirow inserts.
Throws:
IllegalStateException

save

public void save(OrmUjo bo)
          throws IllegalStateException
INSERT object into table.

Throws:
IllegalStateException

update

public int update(OrmUjo bo)
           throws IllegalStateException
Database UPDATE of the modified columns for the selected object.

Returns:
The row count.
Throws:
IllegalStateException
See Also:
OrmUjo.readChangedProperties(boolean)

update

public int update(OrmUjo bo,
                  Criterion criterion)
Database Batch UPDATE of the modified columns along a criterion.
Warning: method does affect to parent objects, see the MetaParams.INHERITANCE_MODE for more information.

Returns:
The row count.
See Also:
OrmUjo.readChangedProperties(boolean)

delete

public <UJO extends OrmUjo> int delete(Criterion<UJO> criterion)
Delete all object object by the criterion from parameter.
Warning 1: method does not remove deleted object from internal cache, however you can call method clearCache() to release all objects from the cache.
Warning 2: method does not delete parent objects, see the MetaParams.INHERITANCE_MODE for more information.

Parameters:
criterion - filter for deleting tables.
Returns:
Returns a number of the realy deleted objects.

delete

public int delete(OrmUjo bo)
Delete an optional object from the parameters.
Warning: method does not remove deleted object from internal cache, however you can call method clearCache() to release all objects from the cache.

Parameters:
bo - Business object to delete, or the null argument as a result of some nullable relation.
Returns:
Returns a number of the removing is OK or the zero if the argumetn is null.

delete

public <UJO extends OrmUjo> int delete(Class<UJO> tableClass,
                                       Criterion<UJO> criterion)
Delete all object object by the criterion from parameter.
Warning: method does not remove deleted object from internal cache, however you can call method clearCache() to release all objects from the cache.

Parameters:
tableClass - Type of table to delete
criterion - filter for deleting tables.
Returns:
Returns a number of the realy deleted objects.

delete

protected <UJO extends OrmUjo> int delete(MetaTable tableModel,
                                          Criterion<UJO> criterion)
Delete all objects object form parameter
Warning: method does not remove deleted object from internal cache, however you can call method clearCache() to release all objects from the cache.

Parameters:
tableModel - Type of table to delete
criterion - filter for deleting tables.
Returns:
Returns a number of the realy deleted objects.

call

protected void call(DbProcedure procedure)
Call the stored procedure


getOrmColumns

protected List<MetaColumn> getOrmColumns(Key... keys)
Convert a key array to a column list.


createPkCriterion

protected Criterion createPkCriterion(OrmUjo bo)
Returns an criterion by a PrimaryKey


getRowCount

public <UJO extends OrmUjo> long getRowCount(Query<UJO> query)
Returns a count of rows


getStatement

public JdbcStatement getStatement(Query query)
Run SQL SELECT by query.


iterateInternal

public <UJO extends OrmUjo> UjoIterator<UJO> iterateInternal(RelationToMany key,
                                                             OrmUjo value)
Iterate key of values

Parameters:
key - Table key type of the RelationToMany.
value - A value type of OrmUjo

getFirstConnection

public final Connection getFirstConnection()
                                    throws IllegalStateException
Get the first Connection where an autocommit is set to false.

Parameters:
databaseIndex - The first database have got the index value: 0 .
Throws:
IllegalStateException

getFirstConnection

public final Connection getFirstConnection(boolean toModify)
                                    throws IllegalStateException
Get the first Connection where an autocommit is set to false.

Parameters:
databaseIndex - The first database have got the index value: 0 .
toModify - By the value false is disabled to assign savepoints in an active transaction.
Throws:
IllegalStateException

getConnection

public final Connection getConnection(int databaseIndex,
                                      boolean toModify)
                               throws IllegalStateException
Get a Connection for a required databse by a database order number (index). The autocommit is set to false.

Parameters:
databaseIndex - The first database have got the index value: 0 .
toModify - By the value false is disabled to assign savepoints in an active transaction.
Throws:
IllegalStateException

getConnection

public final Connection getConnection(MetaDatabase database,
                                      boolean toModify)
                               throws IllegalStateException
Get or create a Connection for a required database with an autocommit na false. If a transaction is running, than assign savepoints.

Parameters:
database - Database meta-model
toModify - By the value false is disabled to assign savepoints in an active transaction.
Throws:
IllegalStateException - An envelope for a run-time SQL exception

getStatement

public JdbcStatement getStatement(MetaDatabase database,
                                  CharSequence sql,
                                  boolean toModify)
                           throws SQLException
Create new statement and assigng Savepoint for a trnasaction sase.

Throws:
SQLException

getStatementCallable

public JdbcStatement getStatementCallable(MetaDatabase database,
                                          String sql,
                                          boolean toModify)
                                   throws SQLException
Create new statement

Throws:
SQLException

load

public <UJO extends OrmUjo> UJO load(Class<UJO> tableType,
                                     Object id)
                        throws NoSuchElementException
Load UJO by a unique id. If a result is not found then a null value is passed.

Parameters:
tableType - Type of Ujo
id - Value ID
Throws:
NoSuchElementException

loadBy

public <UJO extends OrmUjo> UJO loadBy(UJO ujo)
                          throws NoSuchElementException
Load UJO by a unique id. If primary key is null or no result is found then the null value is returned.

Parameters:
tableType - Type of Ujo
id - Value ID
Throws:
NoSuchElementException

reload

public boolean reload(OrmUjo ujo)
Reload values of the persistent object.
Note: If the object has implemented the interface ExtendedOrmUjo than foreign keys are reloaded else a lazy initialization is loaded - for the first key depth.

Parameters:
ujo - The persistent object to relading values.
Returns:
The FALSE value means that the object is missing in the database.

loadInternal

public <UJO extends OrmUjo> UJO loadInternal(Key relatedProperty,
                                             Object id,
                                             boolean mandatory)
                                throws NoSuchElementException
Load UJO by a unique id. If the result is not unique, then an exception is throwed.

Parameters:
relatedProperty - Related key
id - Valid ID
mandatory - If result is mandatory then the method throws an exception if no object was found else returns null;
Throws:
NoSuchElementException

close

public void close()
           throws IllegalStateException
Close and release all DB connections.

Specified by:
close in interface Closeable
Throws:
IllegalStateException - The exception contains a bug from Connection close;

isClosed

public boolean isClosed()
Is the session closed?


findCache

public OrmUjo findCache(Class type,
                        Object pkey)
Find object from internal cache


findCache

public OrmUjo findCache(Class type,
                        Object... pkeys)
Find object from internal cache


clearCache

public void clearCache()
Clear the cache.


clearCache

public final void clearCache(CachePolicy policy)
Clear cache and change its policy.


getParameters

public final MetaParams getParameters()
Returns parameters


isRollbackOnly

public boolean isRollbackOnly()
The rollback is allowed only.

Returns:
The result is true if an inner session attribute is true or a related transaction have got the status equals {link Status#STATUS_ROLLEDBACK}.

markForRolback

public void markForRolback()

readFK

public ForeignKey readFK(OrmUjo ujo,
                         Key<?,? extends OrmUjo> key)
                  throws IllegalStateException
Build new Forign key.

Parameters:
key - The key must be a relalation type of "many to one".
Throws:
IllegalStateException - If a parameter key is not a foreign key.

getDialect

public final SqlDialect getDialect(Class<? extends OrmUjo> ormType)
Check dialecttype


hasDialect

public boolean hasDialect(Class<? extends OrmUjo> ormType,
                          Class<? extends SqlDialect>... dialects)
Returns true, if Corm type have got any from listed dialects

Parameters:
ormType - Entity type
dialects - Entity dialect type
Returns:
Returns true, if Corm type have got any from listed dialects

newClosedSession

public static Session newClosedSession(OrmHandler handler)
Create the closed session


getLazyLoading

public LazyLoading getLazyLoading()
Enable a lazy-loading of related Ujo object. The default value is assigned from the parameter MetaParams#LAZY_LOADING_ENABLED.

Returns:
the lazyLoadingEnabled

setLazyLoading

public void setLazyLoading(LazyLoading lazyLoadingEnabled)
Enable a lazy-loading of related Ujo object. The default value is assigned from the parameter MetaParams#LAZY_LOADING_ENABLED.

Parameters:
lazyLoadingEnabled - the lazyLoadingEnabled to set

checkNotNull

protected void checkNotNull(OrmUjo ujo,
                            String action)
                     throws IllegalArgumentException
Check the Ujo object to not null.

Parameters:
ujo -
action -
Throws:
IllegalArgumentException - Throw the exception if a ujo argument is null.


Copyright 2013, Pavel Ponec