net.java.ao
Class EntityManager

java.lang.Object
  extended by net.java.ao.EntityManager
Direct Known Subclasses:
SearchableEntityManager

public class EntityManager
extends Object

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
EntityManager(DatabaseProvider provider, EntityManagerConfiguration configuration, EventManager eventManager)
          Creates a new instance of EntityManager using the specified DatabaseProvider.
 
Method Summary
<K> int
count(Class<? extends RawEntity<K>> type)
          Counts all entities of the specified type.
<K> int
count(Class<? extends RawEntity<K>> type, Query query)
          Counts all entities of the specified type matching the given Query instance.
<K> int
count(Class<? extends RawEntity<K>> type, String criteria, Object... parameters)
          Counts all entities of the specified type matching the given criteria and parameters.
<T extends RawEntity<K>,K>
T
create(Class<T> type, DBParam... params)
          Creates a new entity of the specified type with the optionally specified initial parameters.
<T extends RawEntity<K>,K>
T
create(Class<T> type, Map<String,Object> params)
          Creates and INSERTs a new entity of the specified type with the given map of parameters.
 void delete(RawEntity<?>... entities)
          Deletes the specified entities from the database.
<T extends RawEntity<K>,K>
T[]
find(Class<T> type)
          Returns all entities of the given type.
<T extends RawEntity<K>,K>
T[]
find(Class<T> type, Query query)
          Selects all entities matching the given type and Query.
<T extends RawEntity<K>,K>
T[]
find(Class<T> type, String criteria, Object... parameters)
          Convenience method to select all entities of the given type with the specified, parameterized criteria.
<T extends RawEntity<K>,K>
T[]
find(Class<T> type, String field, Query query)
          Selects all entities of the specified type which match the given Query.
<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 flush(RawEntity<?>... entities)
          Flushes the value caches of the specified entities along with all of the relevant relations cache entries.
 void flushAll()
          Flushes all value caches contained within entities controlled by this EntityManager instance.
<T extends RawEntity<K>,K>
T[]
get(Class<T> type, K... keys)
          Returns an array of entities of the specified type corresponding to the varargs primary keys.
<T extends RawEntity<K>,K>
T
get(Class<T> type, K key)
          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.
protected
<T extends RawEntity<K>,K>
T
getAndInstantiate(Class<T> type, K key)
          Creates a new instance of the entity of the specified type corresponding to the given primary key.
 Cache getCache()
           
 EventManager getEventManager()
          Returns the event manager in use by this entity manager, cannot but null
 FieldNameConverter getFieldNameConverter()
          Retrieves the FieldNameConverter instance used for name conversion of all entity methods.
 PolymorphicTypeMapper getPolymorphicTypeMapper()
          Retrieves the PolymorphicTypeMapper instance used for flag value conversion of polymorphic types.
 DatabaseProvider getProvider()
          Retrieves the database provider used by this EntityManager for all database operations.
 TableNameConverter getTableNameConverter()
          Retrieves the TableNameConverter instance used for name conversion of all entity types.
 void migrate(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>
T[]
peer(Class<T> type, K... keys)
           
protected
<T extends RawEntity<K>,K>
T
peer(Class<T> type, K key)
           
 void setCache(Cache cache)
          Sets the cache implementation to be used by all entities controlled by this manager.
 void setPolymorphicTypeMapper(PolymorphicTypeMapper typeMapper)
          Specifies the PolymorphicTypeMapper instance to use for all flag value conversion of polymorphic types.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

EntityManager

public EntityManager(DatabaseProvider provider,
                     EntityManagerConfiguration configuration,
                     EventManager eventManager)
Creates a new instance of EntityManager using the specified DatabaseProvider. This constructor initializes the entity and proxy caches based on the given boolean value. If true, the entities will be weakly cached, not maintaining a reference allowing for garbage collection. If false, then strong caching will be used, preventing garbage collection and ensuring the cache is logically complete. If you are concerned about memory, specify true. Otherwise, for maximum performance use false (highly recomended).

Parameters:
provider - the DatabaseProvider to use in all database operations.
configuration - the configuration for this entity manager
eventManager - the event manager to use
Method Detail

migrate

public void migrate(Class<? extends RawEntity<?>>... entities)
             throws SQLException
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:
SchemaGenerator.migrate(DatabaseProvider, SchemaConfiguration, net.java.ao.schema.TableNameConverter, net.java.ao.schema.FieldNameConverter, Class[])

flushAll

public void flushAll()
Flushes all value caches contained within entities controlled by this EntityManager instance. This does not actually remove the entities from the instance cache maintained within this class. Rather, it simply dumps all of the field values cached within the entities themselves (with the exception of the primary key value). This should be used in the case of a complex process outside AO control which may have changed values in the database. If it is at all possible to determine precisely which rows have been changed, the flush(RawEntity[]) } method should be used instead.


flush

public void flush(RawEntity<?>... entities)
Flushes the value caches of the specified entities along with all of the relevant relations cache entries. This should be called after a process outside of AO control may have modified the values in the specified rows. This does not actually remove the entity instances themselves from the instance cache. Rather, it just flushes all of their internally cached values (with the exception of the primary key).


get

public <T extends RawEntity<K>,K> T[] get(Class<T> type,
                                          K... keys)

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's RawEntity inheritence (if inheriting from Entity, this is Integer or int). Thus, the keys 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.

peer

protected <T extends RawEntity<K>,K> T[] peer(Class<T> type,
                                              K... keys)

getAndInstantiate

protected <T extends RawEntity<K>,K> T getAndInstantiate(Class<T> type,
                                                         K key)
Creates a new instance of the entity of the specified type corresponding to the given primary key. This is used by get(Class, Object[])} to create the entity if the instance is not found already in the cache. This method should not be repurposed to perform any caching, since ActiveObjects already assumes that the caching has been performed.

Parameters:
type - 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

public <T extends RawEntity<K>,K> T get(Class<T> type,
                                        K key)
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 overloaded get 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.
See Also:
get(Class, Object[])

peer

protected <T extends RawEntity<K>,K> T peer(Class<T> type,
                                            K key)

create

public <T extends RawEntity<K>,K> T create(Class<T> type,
                                           DBParam... params)
                              throws SQLException

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(EntityManager, Connection, Class, String, boolean, String, DBParam...). This is necessary because not all databases support the JDBC RETURN_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:
DBParam, DatabaseProvider.insertReturningKey(EntityManager, Connection, Class, String, boolean, String, DBParam...)

create

public <T extends RawEntity<K>,K> T create(Class<T> type,
                                           Map<String,Object> params)
                              throws SQLException
Creates and INSERTs a new entity of the specified type with the given map of parameters. This method merely delegates to the create(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(Class, DBParam...)

delete

public void delete(RawEntity<?>... entities)
            throws SQLException

Deletes the specified entities from the database. DELETE statements are called on the rows in the corresponding tables and the entities are removed from the instance cache. 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 of EntityB, 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

find

public <T extends RawEntity<K>,K> T[] find(Class<T> type)
                              throws SQLException
Returns all entities of the given type. This actually peers the call to the find(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 the WHERE.

Example:

manager.find(Person.class, "name LIKE ? OR age > ?", "Joe", 9);

This actually delegates the call to the find(Class, Query) method, properly parameterizing the Query 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 the criteria.
Returns:
An array of entities of the given type which match the specified criteria.
Throws:
SQLException

find

public <T extends RawEntity<K>,K> T[] find(Class<T> type,
                                           Query query)
                              throws SQLException

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 the String parameter.

Parameters:
type - The type of the entities to retrieve.
query - The Query 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 a PreparedStatement using the Query 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 - The Query 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 the criteria.
Returns:
An array of entities of the given type which match the specified query.
Throws:
SQLException

count

public <K> int count(Class<? extends RawEntity<K>> type)
          throws SQLException
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 the criteria.
Returns:
The number of entities of the given type which match the specified criteria.
Throws:
SQLException

count

public <K> int count(Class<? extends RawEntity<K>> type,
                     Query query)
          throws SQLException
Counts all entities of the specified type matching the given Query instance. The SQL runs as a SELECT COUNT(*) to ensure maximum performance.

Parameters:
type - The type of the entities which should be counted.
query - The Query 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

getTableNameConverter

public TableNameConverter getTableNameConverter()
Retrieves the TableNameConverter instance used for name conversion of all entity types.


getFieldNameConverter

public FieldNameConverter getFieldNameConverter()
Retrieves the FieldNameConverter instance used for name conversion of all entity methods.


setPolymorphicTypeMapper

public void setPolymorphicTypeMapper(PolymorphicTypeMapper typeMapper)
Specifies the PolymorphicTypeMapper instance to use for all flag value conversion of polymorphic types. The default type mapper is an empty DefaultPolymorphicTypeMapper instance (thus using the fully qualified classname for all values).

See Also:
getPolymorphicTypeMapper()

getPolymorphicTypeMapper

public PolymorphicTypeMapper getPolymorphicTypeMapper()
Retrieves the PolymorphicTypeMapper instance used for flag value conversion of polymorphic types.

See Also:
setPolymorphicTypeMapper(PolymorphicTypeMapper)

setCache

public void setCache(Cache cache)
Sets the cache implementation to be used by all entities controlled by this manager. Note that this only affects new entities that have not yet been instantiated (may pre-exist as rows in the database). All old entities will continue to use the prior cache.


getCache

public Cache getCache()

getProvider

public DatabaseProvider 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 a Connection instance which can be used for JDBC operations outside of ActiveObjects. Thus:

Connection conn = manager.getProvider().getConnection();
 try {
     // ...
 } finally {
     conn.close();
 }


getEventManager

public EventManager getEventManager()
Returns the event manager in use by this entity manager, cannot but null

Returns:
the event manager in use by this entity manager


Copyright © 2007-2011. All Rights Reserved.