org.hibernate.loader
Class Loader

java.lang.Object
  extended by org.hibernate.loader.Loader
Direct Known Subclasses:
BasicLoader, CustomLoader

public abstract class Loader
extends Object

Abstract superclass of object loading (and querying) strategies. This class implements useful common functionality that concrete loaders delegate to. It is not intended that this functionality would be directly accessed by client code. (Hence, all methods of this class are declared protected or private.) This class relies heavily upon the Loadable interface, which is the contract between this class and EntityPersisters that may be loaded by it.

The present implementation is able to load any number of columns of entities and at most one collection role per query.

Author:
Gavin King
See Also:
Loadable

Constructor Summary
Loader(SessionFactoryImplementor factory)
           
 
Method Summary
protected  String applyLocks(String sql, LockOptions lockOptions, Dialect dialect)
          Append FOR UPDATE OF clause, if necessary.
protected  void applyPostLoadLocks(Object[] row, LockMode[] lockModesArray, SessionImplementor session)
           
protected  boolean areResultSetRowsTransformedImmediately(ResultTransformer transformer)
          Are rows transformed immediately after being read from the ResultSet?
protected  void autoDiscoverTypes(ResultSet rs)
           
protected  int bindNamedParameters(PreparedStatement statement, Map namedParams, int startIndex, SessionImplementor session)
          Bind named parameters to the JDBC prepared statement.
protected  int bindParameterValues(PreparedStatement statement, QueryParameters queryParameters, int startIndex, SessionImplementor session)
          Bind all parameter values into the prepared statement in preparation for execution.
protected  int bindPositionalParameters(PreparedStatement statement, QueryParameters queryParameters, int startIndex, SessionImplementor session)
          Bind positional parameter values to the JDBC prepared statement.
protected  void checkScrollability()
          Check whether the current loader can support returning ScrollableResults.
protected  List doList(SessionImplementor session, QueryParameters queryParameters)
          Actually execute a query, ignoring the query cache
protected  void extractKeysFromResultSet(Loadable[] persisters, QueryParameters queryParameters, ResultSet resultSet, SessionImplementor session, EntityKey[] keys, LockMode[] lockModes, List hydratedObjects)
           
protected  String[] getAliases()
          Get the SQL table aliases of entities whose associations are subselect-loadable, returning null if this loader does not support subselect loading
protected abstract  CollectionAliases[] getCollectionAliases()
           
protected  int[] getCollectionOwners()
          Get the index of the entity that owns the collection, or -1 if there is no owner in the query results (ie.
protected  CollectionPersister[] getCollectionPersisters()
          An (optional) persister for a collection to be initialized; only collection loaders return a non-null value
protected  int[][] getCompositeKeyManyToOneTargetIndices()
           
protected abstract  EntityAliases[] getEntityAliases()
          Get the result set descriptor
protected  boolean[] getEntityEagerPropertyFetches()
          An array indicating whether the entities have eager property fetching enabled.
protected abstract  Loadable[] getEntityPersisters()
          An array of persisters of entity classes contained in each row of results; implemented by all subclasses
 SessionFactoryImplementor getFactory()
           
protected abstract  LockMode[] getLockModes(LockOptions lockOptions)
          What lock options does this load entities with?
 int[] getNamedParameterLocs(String name)
           
protected  EntityType[] getOwnerAssociationTypes()
          An array of the owner types corresponding to the getOwners() returns.
protected  int[] getOwners()
          An array of indexes of the entity that owns a one-to-one association to the entity at the given index (-1 if there is no "owner").
protected  String getQueryIdentifier()
          Identifies the query for statistics reporting, if null, no statistics will be reported
protected  Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session)
          Get the actual object that is returned in the user-visible result list.
protected  List getResultList(List results, ResultTransformer resultTransformer)
           
protected  ResultSet getResultSet(PreparedStatement st, boolean autodiscovertypes, boolean callable, RowSelection selection, SessionImplementor session)
          Fetch a PreparedStatement, call setMaxRows and then execute it, advance to the first result and return an SQL ResultSet
protected abstract  String getSQLString()
          The SQL query string to be called; implemented by all subclasses
protected  boolean hasSubselectLoadableCollections()
           
protected  boolean isSingleRowLoader()
          Return false is this loader is a batch entity loader
protected  boolean isSubselectLoadingEnabled()
           
protected  List list(SessionImplementor session, QueryParameters queryParameters, Set querySpaces, Type[] resultTypes)
          Return the query results, using the query cache, called by subclasses that implement cacheable queries
 void loadCollection(SessionImplementor session, Serializable id, Type type)
          Called by subclasses that initialize collections
 void loadCollectionBatch(SessionImplementor session, Serializable[] ids, Type type)
          Called by wrappers that batch initialize collections
protected  void loadCollectionSubselect(SessionImplementor session, Serializable[] ids, Object[] parameterValues, Type[] parameterTypes, Map namedParameters, Type type)
          Called by subclasses that batch initialize collections
protected  List loadEntity(SessionImplementor session, Object key, Object index, Type keyType, Type indexType, EntityPersister persister)
          Called by subclasses that load entities
protected  List loadEntity(SessionImplementor session, Object id, Type identifierType, Object optionalObject, String optionalEntityName, Serializable optionalIdentifier, EntityPersister persister, LockOptions lockOptions)
          Called by subclasses that load entities
 List loadEntityBatch(SessionImplementor session, Serializable[] ids, Type idType, Object optionalObject, String optionalEntityName, Serializable optionalId, EntityPersister persister, LockOptions lockOptions)
          Called by wrappers that batch load entities
 Object loadSequentialRowsForward(ResultSet resultSet, SessionImplementor session, QueryParameters queryParameters, boolean returnProxies)
          Loads a single logical row from the result set moving forward.
 Object loadSequentialRowsReverse(ResultSet resultSet, SessionImplementor session, QueryParameters queryParameters, boolean returnProxies, boolean isLogicallyAfterLast)
          Loads a single logical row from the result set moving forward.
 Object loadSingleRow(ResultSet resultSet, SessionImplementor session, QueryParameters queryParameters, boolean returnProxies)
          Loads a single row from the result set.
protected  boolean needsFetchingScroll()
          Does the result set to be scrolled contain collection fetches?
protected  void postInstantiate()
          Calculate and cache select-clause suffixes.
protected  PreparedStatement prepareQueryStatement(QueryParameters queryParameters, boolean scroll, SessionImplementor session)
          Obtain a PreparedStatement with all parameters pre-bound.
protected  String preprocessSQL(String sql, QueryParameters parameters, Dialect dialect)
          Modify the SQL, adding lock hints and comments, if necessary
protected  ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer)
          Determine the actual ResultTransformer that will be used to transform query results.
protected  ScrollableResults scroll(QueryParameters queryParameters, Type[] returnTypes, HolderInstantiator holderInstantiator, SessionImplementor session)
          Return the query results, as an instance of ScrollableResults
 String toString()
           
protected  boolean upgradeLocks()
          Does this query return objects that might be already cached by the session, whose lock mode may need upgrading
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Loader

public Loader(SessionFactoryImplementor factory)
Method Detail

getSQLString

protected abstract String getSQLString()
The SQL query string to be called; implemented by all subclasses

Returns:
The sql command this loader should use to get its ResultSet.

getEntityPersisters

protected abstract Loadable[] getEntityPersisters()
An array of persisters of entity classes contained in each row of results; implemented by all subclasses

Returns:
The entity persisters.

getEntityEagerPropertyFetches

protected boolean[] getEntityEagerPropertyFetches()
An array indicating whether the entities have eager property fetching enabled.

Returns:
Eager property fetching indicators.

getOwners

protected int[] getOwners()
An array of indexes of the entity that owns a one-to-one association to the entity at the given index (-1 if there is no "owner"). The indexes contained here are relative to the result of getEntityPersisters().

Returns:
The owner indicators (see discussion above).

getOwnerAssociationTypes

protected EntityType[] getOwnerAssociationTypes()
An array of the owner types corresponding to the getOwners() returns. Indices indicating no owner would be null here.

Returns:
The types for the owners.

getCollectionPersisters

protected CollectionPersister[] getCollectionPersisters()
An (optional) persister for a collection to be initialized; only collection loaders return a non-null value


getCollectionOwners

protected int[] getCollectionOwners()
Get the index of the entity that owns the collection, or -1 if there is no owner in the query results (ie. in the case of a collection initializer) or no collection.


getCompositeKeyManyToOneTargetIndices

protected int[][] getCompositeKeyManyToOneTargetIndices()

getLockModes

protected abstract LockMode[] getLockModes(LockOptions lockOptions)
What lock options does this load entities with?

Parameters:
lockOptions - a collection of lock options specified dynamically via the Query interface

applyLocks

protected String applyLocks(String sql,
                            LockOptions lockOptions,
                            Dialect dialect)
                     throws HibernateException
Append FOR UPDATE OF clause, if necessary. This empty superclass implementation merely returns its first argument.

Throws:
HibernateException

upgradeLocks

protected boolean upgradeLocks()
Does this query return objects that might be already cached by the session, whose lock mode may need upgrading


isSingleRowLoader

protected boolean isSingleRowLoader()
Return false is this loader is a batch entity loader


getAliases

protected String[] getAliases()
Get the SQL table aliases of entities whose associations are subselect-loadable, returning null if this loader does not support subselect loading


preprocessSQL

protected String preprocessSQL(String sql,
                               QueryParameters parameters,
                               Dialect dialect)
                        throws HibernateException
Modify the SQL, adding lock hints and comments, if necessary

Throws:
HibernateException

loadSingleRow

public Object loadSingleRow(ResultSet resultSet,
                            SessionImplementor session,
                            QueryParameters queryParameters,
                            boolean returnProxies)
                     throws HibernateException
Loads a single row from the result set. This is the processing used from the ScrollableResults where no collection fetches were encountered.

Parameters:
resultSet - The result set from which to do the load.
session - The session from which the request originated.
queryParameters - The query parameters specified by the user.
returnProxies - Should proxies be generated
Returns:
The loaded "row".
Throws:
HibernateException

loadSequentialRowsForward

public Object loadSequentialRowsForward(ResultSet resultSet,
                                        SessionImplementor session,
                                        QueryParameters queryParameters,
                                        boolean returnProxies)
                                 throws HibernateException
Loads a single logical row from the result set moving forward. This is the processing used from the ScrollableResults where there were collection fetches encountered; thus a single logical row may have multiple rows in the underlying result set.

Parameters:
resultSet - The result set from which to do the load.
session - The session from which the request originated.
queryParameters - The query parameters specified by the user.
returnProxies - Should proxies be generated
Returns:
The loaded "row".
Throws:
HibernateException

loadSequentialRowsReverse

public Object loadSequentialRowsReverse(ResultSet resultSet,
                                        SessionImplementor session,
                                        QueryParameters queryParameters,
                                        boolean returnProxies,
                                        boolean isLogicallyAfterLast)
                                 throws HibernateException
Loads a single logical row from the result set moving forward. This is the processing used from the ScrollableResults where there were collection fetches encountered; thus a single logical row may have multiple rows in the underlying result set.

Parameters:
resultSet - The result set from which to do the load.
session - The session from which the request originated.
queryParameters - The query parameters specified by the user.
returnProxies - Should proxies be generated
Returns:
The loaded "row".
Throws:
HibernateException

extractKeysFromResultSet

protected void extractKeysFromResultSet(Loadable[] persisters,
                                        QueryParameters queryParameters,
                                        ResultSet resultSet,
                                        SessionImplementor session,
                                        EntityKey[] keys,
                                        LockMode[] lockModes,
                                        List hydratedObjects)
                                 throws SQLException
Throws:
SQLException

applyPostLoadLocks

protected void applyPostLoadLocks(Object[] row,
                                  LockMode[] lockModesArray,
                                  SessionImplementor session)

isSubselectLoadingEnabled

protected boolean isSubselectLoadingEnabled()

hasSubselectLoadableCollections

protected boolean hasSubselectLoadableCollections()

resolveResultTransformer

protected ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer)
Determine the actual ResultTransformer that will be used to transform query results.

Parameters:
resultTransformer - the specified result transformer
Returns:
the actual result transformer

getResultList

protected List getResultList(List results,
                             ResultTransformer resultTransformer)
                      throws QueryException
Throws:
QueryException

areResultSetRowsTransformedImmediately

protected boolean areResultSetRowsTransformedImmediately(ResultTransformer transformer)
Are rows transformed immediately after being read from the ResultSet?

Parameters:
transformer - the specified transformer
Returns:
true, if getResultColumnOrRow() transforms the results; false, otherwise

getResultColumnOrRow

protected Object getResultColumnOrRow(Object[] row,
                                      ResultTransformer transformer,
                                      ResultSet rs,
                                      SessionImplementor session)
                               throws SQLException,
                                      HibernateException
Get the actual object that is returned in the user-visible result list. This empty implementation merely returns its first argument. This is overridden by some subclasses.

Throws:
SQLException
HibernateException

prepareQueryStatement

protected final PreparedStatement prepareQueryStatement(QueryParameters queryParameters,
                                                        boolean scroll,
                                                        SessionImplementor session)
                                                 throws SQLException,
                                                        HibernateException
Obtain a PreparedStatement with all parameters pre-bound. Bind JDBC-style ? parameters, named parameters, and limit parameters.

Throws:
SQLException
HibernateException

bindParameterValues

protected int bindParameterValues(PreparedStatement statement,
                                  QueryParameters queryParameters,
                                  int startIndex,
                                  SessionImplementor session)
                           throws SQLException
Bind all parameter values into the prepared statement in preparation for execution.

Parameters:
statement - The JDBC prepared statement
queryParameters - The encapsulation of the parameter values to be bound.
startIndex - The position from which to start binding parameter values.
session - The originating session.
Returns:
The number of JDBC bind positions actually bound during this method execution.
Throws:
SQLException - Indicates problems performing the binding.

bindPositionalParameters

protected int bindPositionalParameters(PreparedStatement statement,
                                       QueryParameters queryParameters,
                                       int startIndex,
                                       SessionImplementor session)
                                throws SQLException,
                                       HibernateException
Bind positional parameter values to the JDBC prepared statement.

Positional parameters are those specified by JDBC-style ? parameters in the source query. It is (currently) expected that these come before any named parameters in the source query.

Parameters:
statement - The JDBC prepared statement
queryParameters - The encapsulation of the parameter values to be bound.
startIndex - The position from which to start binding parameter values.
session - The originating session.
Returns:
The number of JDBC bind positions actually bound during this method execution.
Throws:
SQLException - Indicates problems performing the binding.
HibernateException - Indicates problems delegating binding to the types.

bindNamedParameters

protected int bindNamedParameters(PreparedStatement statement,
                                  Map namedParams,
                                  int startIndex,
                                  SessionImplementor session)
                           throws SQLException,
                                  HibernateException
Bind named parameters to the JDBC prepared statement.

This is a generic implementation, the problem being that in the general case we do not know enough information about the named parameters to perform this in a complete manner here. Thus this is generally overridden on subclasses allowing named parameters to apply the specific behavior. The most usual limitation here is that we need to assume the type span is always one...

Parameters:
statement - The JDBC prepared statement
namedParams - A map of parameter names to values
startIndex - The position from which to start binding parameter values.
session - The originating session.
Returns:
The number of JDBC bind positions actually bound during this method execution.
Throws:
SQLException - Indicates problems performing the binding.
HibernateException - Indicates problems delegating binding to the types.

getNamedParameterLocs

public int[] getNamedParameterLocs(String name)

getResultSet

protected final ResultSet getResultSet(PreparedStatement st,
                                       boolean autodiscovertypes,
                                       boolean callable,
                                       RowSelection selection,
                                       SessionImplementor session)
                                throws SQLException,
                                       HibernateException
Fetch a PreparedStatement, call setMaxRows and then execute it, advance to the first result and return an SQL ResultSet

Throws:
SQLException
HibernateException

autoDiscoverTypes

protected void autoDiscoverTypes(ResultSet rs)

loadEntity

protected final List loadEntity(SessionImplementor session,
                                Object id,
                                Type identifierType,
                                Object optionalObject,
                                String optionalEntityName,
                                Serializable optionalIdentifier,
                                EntityPersister persister,
                                LockOptions lockOptions)
                         throws HibernateException
Called by subclasses that load entities

Parameters:
persister - only needed for logging
lockOptions -
Throws:
HibernateException

loadEntity

protected final List loadEntity(SessionImplementor session,
                                Object key,
                                Object index,
                                Type keyType,
                                Type indexType,
                                EntityPersister persister)
                         throws HibernateException
Called by subclasses that load entities

Parameters:
persister - only needed for logging
Throws:
HibernateException

loadEntityBatch

public final List loadEntityBatch(SessionImplementor session,
                                  Serializable[] ids,
                                  Type idType,
                                  Object optionalObject,
                                  String optionalEntityName,
                                  Serializable optionalId,
                                  EntityPersister persister,
                                  LockOptions lockOptions)
                           throws HibernateException
Called by wrappers that batch load entities

Parameters:
persister - only needed for logging
lockOptions -
Throws:
HibernateException

loadCollection

public final void loadCollection(SessionImplementor session,
                                 Serializable id,
                                 Type type)
                          throws HibernateException
Called by subclasses that initialize collections

Throws:
HibernateException

loadCollectionBatch

public final void loadCollectionBatch(SessionImplementor session,
                                      Serializable[] ids,
                                      Type type)
                               throws HibernateException
Called by wrappers that batch initialize collections

Throws:
HibernateException

loadCollectionSubselect

protected final void loadCollectionSubselect(SessionImplementor session,
                                             Serializable[] ids,
                                             Object[] parameterValues,
                                             Type[] parameterTypes,
                                             Map namedParameters,
                                             Type type)
                                      throws HibernateException
Called by subclasses that batch initialize collections

Throws:
HibernateException

list

protected List list(SessionImplementor session,
                    QueryParameters queryParameters,
                    Set querySpaces,
                    Type[] resultTypes)
             throws HibernateException
Return the query results, using the query cache, called by subclasses that implement cacheable queries

Throws:
HibernateException

doList

protected List doList(SessionImplementor session,
                      QueryParameters queryParameters)
               throws HibernateException
Actually execute a query, ignoring the query cache

Throws:
HibernateException

checkScrollability

protected void checkScrollability()
                           throws HibernateException
Check whether the current loader can support returning ScrollableResults.

Throws:
HibernateException

needsFetchingScroll

protected boolean needsFetchingScroll()
Does the result set to be scrolled contain collection fetches?

Returns:
True if it does, and thus needs the special fetching scroll functionality; false otherwise.

scroll

protected ScrollableResults scroll(QueryParameters queryParameters,
                                   Type[] returnTypes,
                                   HolderInstantiator holderInstantiator,
                                   SessionImplementor session)
                            throws HibernateException
Return the query results, as an instance of ScrollableResults

Parameters:
queryParameters - The parameters with which the query should be executed.
returnTypes - The expected return types of the query
holderInstantiator - If the return values are expected to be wrapped in a holder, this is the thing that knows how to wrap them.
session - The session from which the scroll request originated.
Returns:
The ScrollableResults instance.
Throws:
HibernateException - Indicates an error executing the query, or constructing the ScrollableResults.

postInstantiate

protected void postInstantiate()
Calculate and cache select-clause suffixes. Must be called by subclasses after instantiation.


getEntityAliases

protected abstract EntityAliases[] getEntityAliases()
Get the result set descriptor


getCollectionAliases

protected abstract CollectionAliases[] getCollectionAliases()

getQueryIdentifier

protected String getQueryIdentifier()
Identifies the query for statistics reporting, if null, no statistics will be reported


getFactory

public final SessionFactoryImplementor getFactory()

toString

public String toString()
Overrides:
toString in class Object


Copyright © 2001-2010 Red Hat, Inc. All Rights Reserved.