Class EntityManager
The root control class for the entire ActiveObjects API. EntityManager
is the source of all RawEntity
objects, as well as the dispatch layer between the entities, the pluggable table name converters, and the
database abstraction layers. This is the entry point for any use of the API.
EntityManager
is designed to be used in an instance fashion with each instance corresponding to a
single database. Thus, rather than a singleton instance or a static factory method, EntityManager
does
have a proper constructor. Any static instance management is left up to the developer using the API.
- Author:
- Daniel Spiewak
-
Constructor Summary
ConstructorsConstructorDescriptionEntityManager
(DatabaseProvider provider, EntityManagerConfiguration configuration) Creates a new instance ofEntityManager
using the specifiedDatabaseProvider
. -
Method Summary
Modifier and TypeMethodDescription<K> int
Counts all entities of the specified type.<K> int
Counts all entities of the specified type matching the given criteria and parameters.<K> int
Counts all entities of the specified type matching the givenQuery
instance.<T extends RawEntity<K>,
K>
voidCreates and INSERTs a batch of new entities represented byrows
of the given type.<T extends RawEntity<K>,
K>
TCreates and INSERTs a new entity of the specified type with the given map of parameters.<T extends RawEntity<K>,
K>
TCreates a new entity of the specified type with the optionally specified initial parameters.void
Deletes the specified entities from the database.<K> int
deleteWithSQL
(Class<? extends RawEntity<K>> type, String criteria, Object... parameters) Deletes rows from the table corresponding totype
.<T extends RawEntity<K>,
K>
T[]Returns all entities of the given type.<T extends RawEntity<K>,
K>
T[]Convenience method to select all entities of the given type with the specified, parameterized criteria.<T extends RawEntity<K>,
K>
T[]Selects all entities of the specified type which match the givenQuery
.<T extends RawEntity<K>,
K>
T[]Selects all entities matching the given type andQuery
.<T extends RawEntity<K>,
K>
TfindSingleEntity
(Class<T> type, String criteria, Object... parameters) Convenience method to select a single entity of the given type with the specified, parameterized criteria.<T extends RawEntity<K>,
K>
T[]findWithSQL
(Class<T> type, String keyField, String sql, Object... parameters) Executes the specified SQL and extracts the given key field, wrapping each row into a instance of the specified type.void
Deprecated.since 0.25.void
flushAll()
Deprecated.since 0.23.void
Deprecated.since 0.23.<T extends RawEntity<K>,
K>
TCleverly overloaded method to return a single entity of the specified type rather than an array in the case where only one ID is passed.<T extends RawEntity<K>,
K>
T[]Returns an array of entities of the specified type corresponding to the varargs primary keys.protected <T extends RawEntity<K>,
K>
TgetAndInstantiate
(EntityInfo<T, K> entityInfo, K key) Creates a new instance of the entity of the specified type corresponding to the given primary key.<K> int
getFastCountEstimate
(Class<? extends RawEntity<K>> type) Gives an approximate count of all entities of the specified type to avoid performance issues.Retrieves theFieldNameConverter
instance used for name conversion of all entity methods.Retrieves thePolymorphicTypeMapper
instance used for flag value conversion of polymorphic types.Retrieves the database provider used by thisEntityManager
for all database operations.RetrievesSchemaConfiguration
used by this entity manager.Retrieves theTableNameConverter
instance used for name conversion of all entity types.void
Convenience method to create the schema for the specified entities using the current settings (table/field name converter and database provider).void
migrateDestructively
(Class<? extends RawEntity<?>>... entities) Convenience method to create the schema for the specified entities using the current settings (table/field name converter and database provider).protected <T extends RawEntity<K>,
K>
Tpeer
(EntityInfo<T, K> entityInfo, K key) protected <T extends RawEntity<K>,
K>
T[]peer
(EntityInfo<T, K> entityInfo, K... keys) protected <T extends RawEntity<K>,
K>
EntityInfo<T,K> resolveEntityInfo
(Class<T> type) void
setPolymorphicTypeMapper
(PolymorphicTypeMapper typeMapper) Specifies thePolymorphicTypeMapper
instance to use for all flag value conversion of polymorphic types.<T extends RawEntity<K>,
K>
voidstream
(Class<T> type, EntityStreamCallback<T, K> streamCallback) Optimised read for large datasets.<T extends RawEntity<K>,
K>
voidstream
(Class<T> type, Query query, EntityStreamCallback<T, K> streamCallback) Selects all entities of the given type and feeds them to the callback, one by one.
-
Constructor Details
-
EntityManager
Creates a new instance ofEntityManager
using the specifiedDatabaseProvider
.- Parameters:
provider
- theDatabaseProvider
to use in all database operations.configuration
- the configuration for this entity manager
-
-
Method Details
-
migrate
Convenience method to create the schema for the specified entities using the current settings (table/field name converter and database provider).- Parameters:
entities
- the "list" of entity classes to consider for migration.- Throws:
SQLException
- See Also:
-
migrateDestructively
Convenience method to create the schema for the specified entities using the current settings (table/field name converter and database provider). Note that if the given entities do not include the full set of entities, or those entities have removed any fields, then the corresponding tables or columns will be dropped, and any data they contained will be lost. Use this at your own risk.- Parameters:
entities
- the "list" of entity classes to consider for migration.- Throws:
SQLException
- See Also:
-
flushAll
Deprecated.since 0.23. EntityManager now no longer caches entities. useflush(RawEntity[])
to flush values for individual entities -
flushEntityCache
Deprecated.since 0.23. EntityManager now no longer caches entities. useflush(RawEntity[])
to flush values for individual entities -
flush
Deprecated.since 0.25. Entities and values now no longer cached. -
get
Returns an array of entities of the specified type corresponding to the varargs primary keys. If an in-memory reference already exists to a corresponding entity (of the specified type and key), it is returned rather than creating a new instance.
If the entity is known to exist in the database, then no checks are performed and the method returns extremely quickly. However, for any key which has not already been verified, a query to the database is performed to determine whether or not the entity exists. If the entity does not exist, then
null
is returned.- Parameters:
type
- The type of the entities to retrieve.keys
- The primary keys corresponding to the entities to retrieve. All keys must be typed according to the generic type parameter of the entity'sRawEntity
inheritence (if inheriting fromEntity
, this isInteger
orint
). Thus, thekeys
array is type-checked at compile time.- Returns:
- An array of entities of the given type corresponding with the specified
primary keys. Any entities which are non-existent will correspond to a
null
value in the resulting array. - Throws:
SQLException
-
peer
protected <T extends RawEntity<K>,K> T[] peer(EntityInfo<T, K> entityInfo, K... keys) throws SQLException- Throws:
SQLException
-
getAndInstantiate
Creates a new instance of the entity of the specified type corresponding to the given primary key. This is used byget(Class, Object[])
} to create the entity.- Parameters:
entityInfo
- The type of the entity to create.key
- The primary key corresponding to the entity instance required.- Returns:
- An entity instance of the specified type and primary key.
-
get
Cleverly overloaded method to return a single entity of the specified type rather than an array in the case where only one ID is passed. This method meerly delegates the call to the overloadedget
method and functions as syntactical sugar.- Parameters:
type
- The type of the entity instance to retrieve.key
- The primary key corresponding to the entity to be retrieved.- Returns:
- An entity instance of the given type corresponding to the specified primary key, or
null
if the entity does not exist in the database. - Throws:
SQLException
- See Also:
-
peer
- Throws:
SQLException
-
create
Creates a new entity of the specified type with the optionally specified initial parameters. This method actually inserts a row into the table represented by the entity type and returns the entity instance which corresponds to that row.
The
DBParam
object parameters are designed to allow the creation of entities which have non-null fields which have no defalut or auto-generated value. Insertion of a row without such field values would of course fail, thus the need for db params. The db params can also be used to set the values for any field in the row, leading to more compact code under certain circumstances.Unless within a transaction, this method will commit to the database immediately and exactly once per call. Thus, care should be taken in the creation of large numbers of entities. There doesn't seem to be a more efficient way to create large numbers of entities, however one should still be aware of the performance implications.
This method delegates the action INSERT action to
DatabaseProvider.insertReturningKey(net.java.ao.EntityManager, java.sql.Connection, java.lang.Class<T>, java.lang.Class<K>, java.lang.String, boolean, java.lang.String, net.java.ao.DBParam...)
. This is necessary because not all databases support the JDBCRETURN_GENERATED_KEYS
constant (e.g. PostgreSQL and HSQLDB). Thus, the database provider itself is responsible for handling INSERTion and retrieval of the correct primary key value.- Parameters:
type
- The type of the entity to INSERT.params
- An optional varargs array of initial values for the fields in the row. These values will be passed to the database within the INSERT statement.- Returns:
- The new entity instance corresponding to the INSERTed row.
- Throws:
SQLException
- See Also:
-
create
public <T extends RawEntity<K>,K> T create(Class<T> type, Map<String, Object> params) throws SQLExceptionCreates and INSERTs a new entity of the specified type with the given map of parameters. This method merely delegates to thecreate(Class, DBParam...)
method. The idea behind having a separate convenience method taking a map is in circumstances with large numbers of parameters or for people familiar with the anonymous inner class constructor syntax who might be more comfortable with creating a map than with passing a number of objects.- Parameters:
type
- The type of the entity to INSERT.params
- A map of parameters to pass to the INSERT.- Returns:
- The new entity instance corresponding to the INSERTed row.
- Throws:
SQLException
- See Also:
-
create
public <T extends RawEntity<K>,K> void create(Class<T> type, List<Map<String, Object>> rows) throws SQLExceptionCreates and INSERTs a batch of new entities represented byrows
of the given type. Each entity corresponds to a single row.- Parameters:
type
- The type of the entity to INSERT.rows
- A list of rows to be INSERTed. A row is represented as a map from column name to its value. All rows must have the same columns.- Throws:
SQLException
-
delete
Deletes the specified entities from the database. DELETE statements are called on the rows in the corresponding tables. The entity instances themselves are not invalidated, but it doesn't even make sense to continue using the instance without a row with which it is paired.
This method does attempt to group the DELETE statements on a per-type basis. Thus, if you pass 5 instances of
EntityA
and two instances ofEntityB
, the following SQL prepared statements will be invoked:DELETE FROM entityA WHERE id IN (?,?,?,?,?); DELETE FROM entityB WHERE id IN (?,?);
Thus, this method scales very well for large numbers of entities grouped into types. However, the execution time increases linearly for each entity of unique type.
- Parameters:
entities
- A varargs array of entities to delete. Method returns immediately if length == 0.- Throws:
SQLException
-
deleteWithSQL
public <K> int deleteWithSQL(Class<? extends RawEntity<K>> type, String criteria, Object... parameters) throws SQLException Deletes rows from the table corresponding to
type
. In contrast todelete(RawEntity[])
, this method allows you to delete rows without creating entities for them first.Example:
manager.deleteWithSQL(Person.class, "name = ?", "Charlie")
The SQL in
criteria
is not parsed or modified in any way by ActiveObjects, and is simply appended to the DELETE statement in a WHERE clause. The above example would cause an SQL statement similar to the following to be executed:DELETE FROM people WHERE name = 'Charlie';
If
criteria
isnull
, this method deletes all rows from the table corresponding totype
.This method does not attempt to determine the set of entities affected by the statement.
- Parameters:
type
- The entity type corresponding to the table to delete from.criteria
- An optional SQL fragment specifying which rows to delete.parameters
- A varargs array of parameters to be passed to the executed prepared statement. The length of this array must match the number of parameters (denoted by the '?' char) incriteria
.- Returns:
- The number of rows deleted from the table.
- Throws:
SQLException
- See Also:
-
find
Returns all entities of the given type. This actually peers the call to thefind(Class, Query)
method.- Parameters:
type
- The type of entity to retrieve.- Returns:
- An array of all entities which correspond to the given type.
- Throws:
SQLException
-
find
public <T extends RawEntity<K>,K> T[] find(Class<T> type, String criteria, Object... parameters) throws SQLException Convenience method to select all entities of the given type with the specified, parameterized criteria. The
criteria
String specified is appended to the SQL prepared statement immediately following theWHERE
.Example:
manager.find(Person.class, "name LIKE ? OR age > ?", "Joe", 9);
This actually delegates the call to the
find(Class, Query)
method, properly parameterizing theQuery
object.- Parameters:
type
- The type of the entities to retrieve.criteria
- A parameterized WHERE statement used to determine the results.parameters
- A varargs array of parameters to be passed to the executed prepared statement. The length of this array must match the number of parameters (denoted by the '?' char) in thecriteria
.- Returns:
- An array of entities of the given type which match the specified criteria.
- Throws:
SQLException
-
findSingleEntity
public <T extends RawEntity<K>,K> T findSingleEntity(Class<T> type, String criteria, Object... parameters) throws SQLException Convenience method to select a single entity of the given type with the specified, parameterized criteria. The
criteria
String specified is appended to the SQL prepared statement immediately following theWHERE
.Example:
manager.findSingleEntity(Person.class, "name LIKE ? OR age > ?", "Joe", 9);
This actually delegates the call to the
find(Class, String, Object...)
method, properly parameterizing theObject
object.- Parameters:
type
- The type of the entities to retrieve.criteria
- A parameterized WHERE statement used to determine the results.parameters
- A varargs array of parameters to be passed to the executed prepared statement. The length of this array must match the number of parameters (denoted by the '?' char) in thecriteria
.- Returns:
- A single entity of the given type which match the specified criteria or null if none returned
- Throws:
SQLException
-
find
Selects all entities matching the given type and
Query
. By default, the entities will be created based on the values within the primary key field for the specified type (this is usually the desired behavior).Example:
manager.find(Person.class, Query.select().where("name LIKE ? OR age > ?", "Joe", 9).limit(10));
This method delegates the call to
find(Class, String, Query)
, passing the primary key field for the given type as theString
parameter.Note that in the case of calling this function with a
Query
with select fields, the first field will be passed tofind(Class, String, Query)
. If this is not the intention, a direct call tofind(Class, String, Query)
should be made instead, with the primary key field specified and present in the select fields.- Parameters:
type
- The type of the entities to retrieve.query
- TheQuery
instance to be used to determine the results.- Returns:
- An array of entities of the given type which match the specified query.
- Throws:
SQLException
-
find
public <T extends RawEntity<K>,K> T[] find(Class<T> type, String field, Query query) throws SQLException Selects all entities of the specified type which match the given
Query
. This method creates aPreparedStatement
using theQuery
instance specified against the table represented by the given type. This query is then executed (with the parameters specified in the query). The method then iterates through the result set and extracts the specified field, mapping an entity of the given type to each row. This array of entities is returned.- Parameters:
type
- The type of the entities to retrieve.field
- The field value to use in the creation of the entities. This is usually the primary key field of the corresponding table.query
- TheQuery
instance to use in determining the results.- Returns:
- An array of entities of the given type which match the specified query.
- Throws:
SQLException
-
findWithSQL
public <T extends RawEntity<K>,K> T[] findWithSQL(Class<T> type, String keyField, String sql, Object... parameters) throws SQLException Executes the specified SQL and extracts the given key field, wrapping each row into a instance of the specified type. The SQL itself is executed as a
PreparedStatement
with the given parameters.Example:
manager.findWithSQL(Person.class, "personID", "SELECT personID FROM chairs WHERE position < ? LIMIT ?", 10, 5);
The SQL is not parsed or modified in any way by ActiveObjects. As such, it is possible to execute database-specific queries using this method without realizing it. For example, the above query will not run on MS SQL Server or Oracle, due to the lack of a LIMIT clause in their SQL implementation. As such, be extremely careful about what SQL is executed using this method, or else be conscious of the fact that you may be locking yourself to a specific DBMS.
- Parameters:
type
- The type of the entities to retrieve.keyField
- The field value to use in the creation of the entities. This is usually the primary key field of the corresponding table.sql
- The SQL statement to execute.parameters
- A varargs array of parameters to be passed to the executed prepared statement. The length of this array must match the number of parameters (denoted by the '?' char) in thecriteria
.- Returns:
- An array of entities of the given type which match the specified query.
- Throws:
SQLException
-
stream
public <T extends RawEntity<K>,K> void stream(Class<T> type, EntityStreamCallback<T, K> streamCallback) throws SQLExceptionOptimised read for large datasets. This method will stream all rows for the given type to the given callback.
Please see
stream(Class, Query, EntityStreamCallback)
for details / limitations.- Parameters:
type
- The type of the entities to retrieve.streamCallback
- The receiver of the data, will be passed one entity per returned row- Throws:
SQLException
-
stream
public <T extends RawEntity<K>,K> void stream(Class<T> type, Query query, EntityStreamCallback<T, K> streamCallback) throws SQLExceptionSelects all entities of the given type and feeds them to the callback, one by one. The entities are slim, read-only representations of the data. They only supports getters or designated
Accessor
methods. Calling setters orsave
will result in an exception. Other method calls will be ignored. The proxies do not support lazy-loading of related entities.Only the fields specified in the Query are loaded. Since lazy loading is not supported, calls to unspecified getters will return null (or AO's defaults in case of primitives)
This call is optimised for efficient read operations on large datasets. For best memory usage, do not buffer the entities passed to the callback but process and discard them directly.
Unlike regular Entities, the read only implementations do not support flushing/refreshing. The data is a snapshot view at the time of query.
- Parameters:
type
- The type of the entities to retrieve.query
-streamCallback
- The receiver of the data, will be passed one entity per returned row- Throws:
SQLException
-
count
Counts all entities of the specified type. This method is actually a delegate for:count(Class<? extends Entity>, Query)
- Parameters:
type
- The type of the entities which should be counted.- Returns:
- The number of entities of the specified type.
- Throws:
SQLException
-
count
public <K> int count(Class<? extends RawEntity<K>> type, String criteria, Object... parameters) throws SQLException Counts all entities of the specified type matching the given criteria and parameters. This is a convenience method for:count(type, Query.select().where(criteria, parameters))
- Parameters:
type
- The type of the entities which should be counted.criteria
- A parameterized WHERE statement used to determine the result set which will be counted.parameters
- A varargs array of parameters to be passed to the executed prepared statement. The length of this array must match the number of parameters (denoted by the '?' char) in thecriteria
.- Returns:
- The number of entities of the given type which match the specified criteria.
- Throws:
SQLException
-
count
Counts all entities of the specified type matching the givenQuery
instance. The SQL runs as aSELECT COUNT(*)
to ensure maximum performance.- Parameters:
type
- The type of the entities which should be counted.query
- TheQuery
instance used to determine the result set which will be counted.- Returns:
- The number of entities of the given type which match the specified query.
- Throws:
SQLException
-
getFastCountEstimate
public <K> int getFastCountEstimate(Class<? extends RawEntity<K>> type) throws SQLException, FailedFastCountException Gives an approximate count of all entities of the specified type to avoid performance issues.DO NOT use this API if you need an exact count. For a guaranteed accurate count, use
count(Class)
.Accuracy may depend on how long the last DB cleanup job was run
- Parameters:
type
- The type of the entities which should be counted- Returns:
- The approximate number of entities of the given type
- Throws:
FailedFastCountException
- means something went wrong while attempting to get a fast countSQLException
- Since:
- 4.1 and 5.3 but not in 5.0 or 5.1
-
getNameConverters
-
resolveEntityInfo
-
getTableNameConverter
Retrieves theTableNameConverter
instance used for name conversion of all entity types. -
getFieldNameConverter
Retrieves theFieldNameConverter
instance used for name conversion of all entity methods. -
setPolymorphicTypeMapper
Specifies thePolymorphicTypeMapper
instance to use for all flag value conversion of polymorphic types. The default type mapper is an emptyDefaultPolymorphicTypeMapper
instance (thus using the fully qualified classname for all values).- See Also:
-
getPolymorphicTypeMapper
Retrieves thePolymorphicTypeMapper
instance used for flag value conversion of polymorphic types. -
getProvider
Retrieves the database provider used by this
EntityManager
for all database operations. This method can be used reliably to obtain a database provider and hence aConnection
instance which can be used for JDBC operations outside of ActiveObjects. Thus:Connection conn = manager.getProvider().getConnection(); try { // ... } finally { conn.close(); }
-
getSchemaConfiguration
RetrievesSchemaConfiguration
used by this entity manager.- Returns:
- the
SchemaConfiguration
-