net.java.ao
Class EntityManager

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

public class EntityManager
extends java.lang.Object

The root control class for the entire ActiveObjects API. EntityManager is the source of all Entity 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.

As a side note, ActiveObjects can optionally log all SQL queries prior to their execution. This query logging is done with the Java Logging API using the Logger instance for the net.java.ao package. This logging is disabled by default by the EntityManager static initializer. Thus, if it is desirable to log the SQL statements, the Logger level must be set to Level.FINE after the EntityManager class is first used. This usually means setting the log level after the constructer has been called.

Author:
Daniel Spiewak

Constructor Summary
EntityManager(DatabaseProvider provider)
          Creates a new instance of EntityManager using the specified DatabaseProvider.
EntityManager(DatabaseProvider provider, boolean weaklyCache)
          Creates a new instance of EntityManager using the specified DatabaseProvider.
EntityManager(java.lang.String uri, java.lang.String username, java.lang.String password)
          Creates a new instance of EntityManager by auto-magically finding a DatabaseProvider instnace for the specified JDBC URI, username and password.
 
Method Summary
 int count(java.lang.Class<? extends Entity> type)
          Counts all entities of the specified type.
 int count(java.lang.Class<? extends Entity> type, Query query)
          Counts all entities of the specified type matching the given Query instance.
 int count(java.lang.Class<? extends Entity> type, java.lang.String criteria, java.lang.Object... parameters)
          Counts all entities of the specified type matching the given criteria and parameters.
<T extends Entity>
T
create(java.lang.Class<T> type, DBParam... params)
          Creates a new entity of the specified type with the optionally specified initial parameters.
 void delete(Entity... entities)
          Deletes the specified entities from the database.
<T extends Entity>
T[]
find(java.lang.Class<T> type)
          Returns all entities of the given type.
<T extends Entity>
T[]
find(java.lang.Class<T> type, Query query)
           
<T extends Entity>
T[]
find(java.lang.Class<T> type, java.lang.String criteria, java.lang.Object... parameters)
          Convenience method to select all entities of the given type with the specified, parameterized criteria.
<T extends Entity>
T[]
find(java.lang.Class<T> type, java.lang.String field, Query query)
          Selects all entities of the specified type which match the given Query.
<T extends Entity>
T[]
findWithSQL(java.lang.Class<T> type, java.lang.String idField, java.lang.String sql, java.lang.Object... parameters)
          Executes the specified SQL and extracts the given idfield, wrapping each row into a instance of the specified type.
 void flush(Entity... entities)
           
 void flushAll()
           
<T extends Entity>
T[]
get(java.lang.Class<T> type, int... ids)
          Returns an array of entities of the specified type corresponding to the varargs ids.
<T extends Entity>
T
get(java.lang.Class<T> type, int id)
          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 Entity>
T
getAndInstantiate(java.lang.Class<T> type, int id)
           
 FieldNameConverter getFieldNameConverter()
           
 DatabaseProvider getProvider()
           
protected
<T extends Entity>
net.java.ao.EntityProxy<T>
getProxyForEntity(T entity)
           
 RSCachingStrategy getRSCachingStrategy()
           
 TableNameConverter getTableNameConverter()
          Retrieves the TableNameConverter instance used for name conversion of all entity types.
 void migrate(java.lang.Class<? extends Entity>... entities)
          Convenience method to create the schema for the specified entities using the current settings (name converter and database provider).
 void setFieldNameConverter(FieldNameConverter fieldNameConverter)
           
 void setRSCachingStrategy(RSCachingStrategy rsStrategy)
           
 void setTableNameConverter(TableNameConverter tableNameConverter)
          Specifies the TableNameConverter instance to use for name conversion of all entity 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)
Creates a new instance of EntityManager using the specified DatabaseProvider. This constructor intializes the entity cache, as well as creates the default TableNameConverter (the default is CamelCaseTableNameConverter, which is non-pluralized). The provider instance is immutable once set using this constructor. By default (using this constructor), all entities are strongly cached, meaning references are held to the instances, preventing garbage collection.

See Also:
EntityManager(DatabaseProvider, boolean)

EntityManager

public EntityManager(DatabaseProvider provider,
                     boolean weaklyCache)
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 leaks, specify true. Otherwise, for maximum performance use false.


EntityManager

public EntityManager(java.lang.String uri,
                     java.lang.String username,
                     java.lang.String password)
Creates a new instance of EntityManager by auto-magically finding a DatabaseProvider instnace for the specified JDBC URI, username and password. The auto-magically determined instance is pooled by default (if a supported connection pooling library is available on the classpath).

See Also:
EntityManager(DatabaseProvider), DatabaseProvider.getInstance(String, String, String)
Method Detail

migrate

public void migrate(java.lang.Class<? extends Entity>... entities)
             throws java.sql.SQLException
Convenience method to create the schema for the specified entities using the current settings (name converter and database provider).

Throws:
java.sql.SQLException
See Also:
net.java.ao.schema.Generator#migrate(DatabaseProvider, TableNameConverter, Class...)

flushAll

public void flushAll()

flush

public void flush(Entity... entities)

get

public <T extends Entity> T[] get(java.lang.Class<T> type,
                                  int... ids)

Returns an array of entities of the specified type corresponding to the varargs ids. If an in-memory reference already exists to a corresponding entity (of the specified type and id), it is returned rather than creating a new instance.

No checks are performed to ensure that the id actually exists in the database for the specified object. Thus, this method is solely a Java memory state modifying method. There is not database access involved. The upshot of this is that the method is very very fast. The flip side of course is that one could conceivably maintain entities which reference non-existant database rows.


getAndInstantiate

protected <T extends Entity> T getAndInstantiate(java.lang.Class<T> type,
                                                 int id)

get

public <T extends Entity> T get(java.lang.Class<T> type,
                                int id)
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.

See Also:
get(Class, int...)

create

public <T extends Entity> T create(java.lang.Class<T> type,
                                   DBParam... params)
                        throws java.sql.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.

Throws:
java.sql.SQLException

delete

public void delete(Entity... entities)
            throws java.sql.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 prepared statement SQL 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 scales linearly for each entity of unique type.

Throws:
java.sql.SQLException

find

public <T extends Entity> T[] find(java.lang.Class<T> type)
                        throws java.sql.SQLException
Returns all entities of the given type. This actually peers the call to the find(Class, Query) method.

Throws:
java.sql.SQLException

find

public <T extends Entity> T[] find(java.lang.Class<T> type,
                                   java.lang.String criteria,
                                   java.lang.Object... parameters)
                        throws java.sql.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 peers the call to the find(Class, Query) method, properly parameterizing the Query object.

Throws:
java.sql.SQLException

find

public <T extends Entity> T[] find(java.lang.Class<T> type,
                                   Query query)
                        throws java.sql.SQLException
Throws:
java.sql.SQLException

find

public <T extends Entity> T[] find(java.lang.Class<T> type,
                                   java.lang.String field,
                                   Query query)
                        throws java.sql.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.

Throws:
java.sql.SQLException

findWithSQL

public <T extends Entity> T[] findWithSQL(java.lang.Class<T> type,
                                          java.lang.String idField,
                                          java.lang.String sql,
                                          java.lang.Object... parameters)
                               throws java.sql.SQLException
Executes the specified SQL and extracts the given idfield, wrapping each row into a instance of the specified type. The SQL itself is executed as a PreparedStatement with the given parameters.

Throws:
java.sql.SQLException

count

public int count(java.lang.Class<? extends Entity> type)
          throws java.sql.SQLException
Counts all entities of the specified type. This method is actually a delegate for the count(Class<? extends Entity>, Query) method.

Throws:
java.sql.SQLException

count

public int count(java.lang.Class<? extends Entity> type,
                 java.lang.String criteria,
                 java.lang.Object... parameters)
          throws java.sql.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))

Throws:
java.sql.SQLException

count

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

Throws:
java.sql.SQLException

setTableNameConverter

public void setTableNameConverter(TableNameConverter tableNameConverter)

Specifies the TableNameConverter instance to use for name conversion of all entity types. Name conversion is the process of determining the appropriate table name from an arbitrary Entity class.

The default nameConverter is CamelCaseTableNameConverter.


getTableNameConverter

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

See Also:
setTableNameConverter(TableNameConverter)

setFieldNameConverter

public void setFieldNameConverter(FieldNameConverter fieldNameConverter)

getFieldNameConverter

public FieldNameConverter getFieldNameConverter()

setRSCachingStrategy

public void setRSCachingStrategy(RSCachingStrategy rsStrategy)

getRSCachingStrategy

public RSCachingStrategy getRSCachingStrategy()

getProvider

public DatabaseProvider getProvider()

getProxyForEntity

protected <T extends Entity> net.java.ao.EntityProxy<T> getProxyForEntity(T entity)