|
The Spring Framework | |||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
java.lang.Objectorg.springframework.orm.hibernate3.HibernateAccessor
org.springframework.orm.hibernate3.HibernateTemplate
public class HibernateTemplate
Helper class that simplifies Hibernate data access code. Automatically
converts HibernateExceptions into DataAccessExceptions, following the
org.springframework.dao exception hierarchy.
NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can
also be coded in plain Hibernate style. Hence, for newly started projects,
consider adopting the standard Hibernate3 style of coding data access objects
instead, based on SessionFactory.getCurrentSession().
(Spring's LocalSessionFactoryBean automatically supports Spring transaction
management for the Hibernate3 getCurrentSession() method.)
The central method is execute, supporting Hibernate access code
implementing the HibernateCallback interface. It provides Hibernate Session
handling such that neither the HibernateCallback implementation nor the calling
code needs to explicitly care about retrieving/closing Hibernate Sessions,
or handling Session lifecycle exceptions. For typical single step actions,
there are various convenience methods (find, load, saveOrUpdate, delete).
Can be used within a service implementation via direct instantiation with a SessionFactory reference, or get prepared in an application context and given to services as bean reference. Note: The SessionFactory should always be configured as bean in the application context, in the first case given to the service directly, in the second case to the prepared template.
This class can be considered as direct alternative to working with the raw
Hibernate3 Session API (through SessionFactory.getCurrentSession()).
The major advantage is its automatic conversion to DataAccessExceptions, the
major disadvantage that no checked application exceptions can get thrown from
within data access code. Corresponding checks and the actual throwing of such
exceptions can often be deferred to after callback execution, though.
Note that even if HibernateTransactionManager is used for transaction
demarcation in higher-level services, all those services above the data
access layer don't need to be Hibernate-aware. Setting such a special
PlatformTransactionManager is a configuration issue: For example,
switching to JTA is just a matter of Spring configuration (use
JtaTransactionManager instead) that does not affect application code.
LocalSessionFactoryBean is the preferred way of obtaining a reference
to a specific Hibernate SessionFactory, at least in a non-EJB environment.
The Spring application context will manage its lifecycle, initializing and
shutting down the factory as part of the application.
Note that operations that return an Iterator (i.e. iterate)
are supposed to be used within Spring-driven or JTA-driven transactions
(with HibernateTransactionManager, JtaTransactionManager, or EJB CMT).
Else, the Iterator won't be able to read results from its ResultSet anymore,
as the underlying Hibernate Session will already have been closed.
Lazy loading will also just work with an open Hibernate Session,
either within a transaction or within OpenSessionInViewFilter/Interceptor.
Furthermore, some operations just make sense within transactions,
for example: contains, evict, lock,
flush, clear.
SessionFactory.getCurrentSession(),
HibernateAccessor.setSessionFactory(org.hibernate.SessionFactory),
HibernateCallback,
Session,
LocalSessionFactoryBean,
HibernateTransactionManager,
JtaTransactionManager,
OpenSessionInViewFilter,
OpenSessionInViewInterceptor| Field Summary |
|---|
| Fields inherited from class org.springframework.orm.hibernate3.HibernateAccessor |
|---|
FLUSH_ALWAYS, FLUSH_AUTO, FLUSH_COMMIT, FLUSH_EAGER, FLUSH_NEVER, logger |
| Constructor Summary | |
|---|---|
HibernateTemplate()
Create a new HibernateTemplate instance. |
|
HibernateTemplate(SessionFactory sessionFactory)
Create a new HibernateTemplate instance. |
|
HibernateTemplate(SessionFactory sessionFactory,
boolean allowCreate)
Create a new HibernateTemplate instance. |
|
| Method Summary | |
|---|---|
protected void |
applyNamedParameterToQuery(Query queryObject,
String paramName,
Object value)
Apply the given name parameter to the given Query object. |
int |
bulkUpdate(String queryString)
Update/delete all objects according to the given query. |
int |
bulkUpdate(String queryString,
Object value)
Update/delete all objects according to the given query, binding one value to a "?" |
int |
bulkUpdate(String queryString,
Object[] values)
Update/delete all objects according to the given query, binding a number of values to "?" |
protected void |
checkWriteOperationAllowed(Session session)
Check whether write operations are allowed on the given Session. |
void |
clear()
Remove all objects from the Session cache, and
cancel all pending saves, updates and deletes. |
void |
closeIterator(Iterator it)
Immediately close an Iterator created by any of the various
iterate(..) |
boolean |
contains(Object entity)
Check whether the given object is in the Session cache. |
protected Session |
createSessionProxy(Session session)
Create a close-suppressing proxy for the given Hibernate Session. |
void |
delete(Object entity)
Delete the given persistent instance. |
void |
delete(Object entity,
LockMode lockMode)
Delete the given persistent instance. |
void |
deleteAll(Collection entities)
Delete all given persistent instances. |
Filter |
enableFilter(String filterName)
Return an enabled Hibernate Filter for the given filter name. |
void |
evict(Object entity)
Remove the given object from the Session cache. |
Object |
execute(HibernateCallback action)
Execute the action specified by the given action object within a Session. |
Object |
execute(HibernateCallback action,
boolean exposeNativeSession)
Execute the action specified by the given action object within a Session. |
List |
executeFind(HibernateCallback action)
Execute the specified action assuming that the result object is a List. |
List |
find(String queryString)
Execute an HQL query. |
List |
find(String queryString,
Object value)
Execute an HQL query, binding one value to a "?" |
List |
find(String queryString,
Object[] values)
Execute an HQL query, binding a number of values to "?" |
List |
findByCriteria(DetachedCriteria criteria)
Execute a query based on a given Hibernate criteria object. |
List |
findByCriteria(DetachedCriteria criteria,
int firstResult,
int maxResults)
Execute a query based on the given Hibernate criteria object. |
List |
findByExample(Object exampleEntity)
Execute a query based on the given example entity object. |
List |
findByExample(Object exampleEntity,
int firstResult,
int maxResults)
Execute a query based on a given example entity object. |
List |
findByNamedParam(String queryString,
String[] paramNames,
Object[] values)
Execute an HQL query, binding a number of values to ":" named parameters in the query string. |
List |
findByNamedParam(String queryString,
String paramName,
Object value)
Execute an HQL query, binding one value to a ":" named parameter in the query string. |
List |
findByNamedQuery(String queryName)
Execute a named query. |
List |
findByNamedQuery(String queryName,
Object value)
Execute a named query, binding one value to a "?" |
List |
findByNamedQuery(String queryName,
Object[] values)
Execute a named query binding a number of values to "?" |
List |
findByNamedQueryAndNamedParam(String queryName,
String[] paramNames,
Object[] values)
Execute a named query, binding a number of values to ":" named parameters in the query string. |
List |
findByNamedQueryAndNamedParam(String queryName,
String paramName,
Object value)
Execute a named query, binding one value to a ":" named parameter in the query string. |
List |
findByNamedQueryAndValueBean(String queryName,
Object valueBean)
Execute a named query, binding the properties of the given bean to ":" named parameters in the query string. |
List |
findByValueBean(String queryString,
Object valueBean)
Execute an HQL query, binding the properties of the given bean to named parameters in the query string. |
void |
flush()
Flush all pending saves, updates and deletes to the database. |
Object |
get(Class entityClass,
Serializable id)
Return the persistent instance of the given entity class with the given identifier, or null if not found. |
Object |
get(Class entityClass,
Serializable id,
LockMode lockMode)
Return the persistent instance of the given entity class with the given identifier, or null if not found. |
Object |
get(String entityName,
Serializable id)
Return the persistent instance of the given entity class with the given identifier, or null if not found. |
Object |
get(String entityName,
Serializable id,
LockMode lockMode)
Return the persistent instance of the given entity class with the given identifier, or null if not found. |
int |
getFetchSize()
Return the fetch size specified for this HibernateTemplate. |
int |
getMaxResults()
Return the maximum number of rows specified for this HibernateTemplate. |
String |
getQueryCacheRegion()
Return the name of the cache region for queries executed by this template. |
protected Session |
getSession()
Return a Session for use by this template. |
void |
initialize(Object proxy)
Force initialization of a Hibernate proxy or persistent collection. |
boolean |
isAllowCreate()
Return if a new Session should be created if no thread-bound found. |
boolean |
isAlwaysUseNewSession()
Return whether to always use a new Hibernate Session for this template. |
boolean |
isCacheQueries()
Return whether to cache all queries executed by this template. |
boolean |
isCheckWriteOperations()
Return whether to check that the Hibernate Session is not in read-only mode in case of write operations (save/update/delete). |
boolean |
isExposeNativeSession()
Return whether to expose the native Hibernate Session to HibernateCallback code, or rather a Session proxy. |
Iterator |
iterate(String queryString)
Execute a query for persistent instances. |
Iterator |
iterate(String queryString,
Object value)
Execute a query for persistent instances, binding one value to a "?" |
Iterator |
iterate(String queryString,
Object[] values)
Execute a query for persistent instances, binding a number of values to "?" |
Object |
load(Class entityClass,
Serializable id)
Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found. |
Object |
load(Class entityClass,
Serializable id,
LockMode lockMode)
Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found. |
void |
load(Object entity,
Serializable id)
Load the persistent instance with the given identifier into the given object, throwing an exception if not found. |
Object |
load(String entityName,
Serializable id)
Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found. |
Object |
load(String entityName,
Serializable id,
LockMode lockMode)
Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found. |
List |
loadAll(Class entityClass)
Return all persistent instances of the given entity class. |
void |
lock(Object entity,
LockMode lockMode)
Obtain the specified lock level upon the given object, implicitly checking whether the corresponding database entry still exists. |
void |
lock(String entityName,
Object entity,
LockMode lockMode)
Obtain the specified lock level upon the given object, implicitly checking whether the corresponding database entry still exists. |
Object |
merge(Object entity)
Copy the state of the given object onto the persistent object with the same identifier. |
Object |
merge(String entityName,
Object entity)
Copy the state of the given object onto the persistent object with the same identifier. |
void |
persist(Object entity)
Persist the given transient instance. |
void |
persist(String entityName,
Object entity)
Persist the given transient instance. |
protected void |
prepareCriteria(Criteria criteria)
Prepare the given Criteria object, applying cache settings and/or a transaction timeout. |
protected void |
prepareQuery(Query queryObject)
Prepare the given Query object, applying cache settings and/or a transaction timeout. |
void |
refresh(Object entity)
Re-read the state of the given persistent instance. |
void |
refresh(Object entity,
LockMode lockMode)
Re-read the state of the given persistent instance. |
void |
replicate(Object entity,
ReplicationMode replicationMode)
Persist the state of the given detached instance according to the given replication mode, reusing the current identifier value. |
void |
replicate(String entityName,
Object entity,
ReplicationMode replicationMode)
Persist the state of the given detached instance according to the given replication mode, reusing the current identifier value. |
Serializable |
save(Object entity)
Persist the given transient instance. |
Serializable |
save(String entityName,
Object entity)
Persist the given transient instance. |
void |
saveOrUpdate(Object entity)
Save or update the given persistent instance, according to its id (matching the configured "unsaved-value"?). |
void |
saveOrUpdate(String entityName,
Object entity)
Save or update the given persistent instance, according to its id (matching the configured "unsaved-value"?). |
void |
saveOrUpdateAll(Collection entities)
Save or update all given persistent instances, according to its id (matching the configured "unsaved-value"?). |
void |
setAllowCreate(boolean allowCreate)
Set if a new Session should be created when no transactional
Session can be found for the current thread. |
void |
setAlwaysUseNewSession(boolean alwaysUseNewSession)
Set whether to always use a new Hibernate Session for this template. |
void |
setCacheQueries(boolean cacheQueries)
Set whether to cache all queries executed by this template. |
void |
setCheckWriteOperations(boolean checkWriteOperations)
Set whether to check that the Hibernate Session is not in read-only mode in case of write operations (save/update/delete). |
void |
setExposeNativeSession(boolean exposeNativeSession)
Set whether to expose the native Hibernate Session to HibernateCallback code. |
void |
setFetchSize(int fetchSize)
Set the fetch size for this HibernateTemplate. |
void |
setMaxResults(int maxResults)
Set the maximum number of rows for this HibernateTemplate. |
void |
setQueryCacheRegion(String queryCacheRegion)
Set the name of the cache region for queries executed by this template. |
void |
update(Object entity)
Update the given persistent instance, associating it with the current Hibernate Session. |
void |
update(Object entity,
LockMode lockMode)
Update the given persistent instance, associating it with the current Hibernate Session. |
void |
update(String entityName,
Object entity)
Update the given persistent instance, associating it with the current Hibernate Session. |
void |
update(String entityName,
Object entity,
LockMode lockMode)
Update the given persistent instance, associating it with the current Hibernate Session. |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
|---|
public HibernateTemplate()
public HibernateTemplate(SessionFactory sessionFactory)
sessionFactory - SessionFactory to create Sessions
public HibernateTemplate(SessionFactory sessionFactory,
boolean allowCreate)
sessionFactory - SessionFactory to create SessionsallowCreate - if a non-transactional Session should be created when no
transactional Session can be found for the current thread| Method Detail |
|---|
public void setAllowCreate(boolean allowCreate)
Session should be created when no transactional
Session can be found for the current thread.
The default value is "true".
HibernateTemplate is aware of a corresponding
Session bound to the current thread, for example when using
HibernateTransactionManager. If allowCreate is
true, a new non-transactional Session will be
created if none is found, which needs to be closed at the end of the operation.
If false, an IllegalStateException will get thrown in
this case.
SessionFactoryUtils.getSession(SessionFactory, boolean)public boolean isAllowCreate()
public void setAlwaysUseNewSession(boolean alwaysUseNewSession)
Within a transaction, a new Hibernate Session used by this template will participate in the transaction through using the same JDBC Connection. In such a scenario, multiple Sessions will participate in the same database transaction.
Turn this on for operations that are supposed to always execute independently, without side effects caused by a shared Hibernate Session.
public boolean isAlwaysUseNewSession()
public void setExposeNativeSession(boolean exposeNativeSession)
Default is "false": a Session proxy will be returned, suppressing
close calls and automatically applying query cache
settings and transaction timeouts.
HibernateCallback,
Session,
setCacheQueries(boolean),
setQueryCacheRegion(java.lang.String),
prepareQuery(org.hibernate.Query),
prepareCriteria(org.hibernate.Criteria)public boolean isExposeNativeSession()
public void setCheckWriteOperations(boolean checkWriteOperations)
Default is "true", for fail-fast behavior when attempting write operations within a read-only transaction. Turn this off to allow save/update/delete on a Session with flush mode NEVER.
HibernateAccessor.setFlushMode(int),
checkWriteOperationAllowed(org.hibernate.Session),
TransactionDefinition.isReadOnly()public boolean isCheckWriteOperations()
public void setCacheQueries(boolean cacheQueries)
If this is "true", all Query and Criteria objects created by this template will be marked as cacheable (including all queries through find methods).
To specify the query region to be used for queries cached by this template, set the "queryCacheRegion" property.
setQueryCacheRegion(java.lang.String),
Query.setCacheable(boolean),
Criteria.setCacheable(boolean)public boolean isCacheQueries()
public void setQueryCacheRegion(String queryCacheRegion)
If this is specified, it will be applied to all Query and Criteria objects created by this template (including all queries through find methods).
The cache region will not take effect unless queries created by this template are configured to be cached via the "cacheQueries" property.
setCacheQueries(boolean),
Query.setCacheRegion(java.lang.String),
Criteria.setCacheRegion(java.lang.String)public String getQueryCacheRegion()
public void setFetchSize(int fetchSize)
Default is 0, indicating to use the JDBC driver's default.
public int getFetchSize()
public void setMaxResults(int maxResults)
Default is 0, indicating to use the JDBC driver's default.
public int getMaxResults()
public Object execute(HibernateCallback action)
throws DataAccessException
HibernateOperationsSession.
Application exceptions thrown by the action object get propagated to the caller (can only be unchecked). Hibernate exceptions are transformed into appropriate DAO ones. Allows for returning a result object, that is a domain object or a collection of domain objects.
Note: Callback code is not supposed to handle transactions itself!
Use an appropriate transaction manager like
HibernateTransactionManager. Generally, callback code must not
touch any Session lifecycle methods, like close,
disconnect, or reconnect, to let the template do its work.
execute in interface HibernateOperationsaction - callback object that specifies the Hibernate action
null
DataAccessException - in case of Hibernate errorsHibernateTransactionManager,
org.springframework.dao,
org.springframework.transaction,
Session
public List executeFind(HibernateCallback action)
throws DataAccessException
HibernateOperationsList.
This is a convenience method for executing Hibernate find calls or queries within an action.
executeFind in interface HibernateOperationsaction - calback object that specifies the Hibernate action
null
DataAccessException - in case of Hibernate errors
public Object execute(HibernateCallback action,
boolean exposeNativeSession)
throws DataAccessException
action - callback object that specifies the Hibernate actionexposeNativeSession - whether to expose the native Hibernate Session
to callback code
null
DataAccessException - in case of Hibernate errorsprotected Session getSession()
Returns a new Session in case of "alwaysUseNewSession" (using the same JDBC Connection as a transactional Session, if applicable), a pre-bound Session in case of "allowCreate" turned off, and a pre-bound or new Session else (new only if no transactional or otherwise pre-bound Session exists).
SessionFactoryUtils.getSession(org.hibernate.SessionFactory, boolean),
SessionFactoryUtils.getNewSession(org.hibernate.SessionFactory),
setAlwaysUseNewSession(boolean),
setAllowCreate(boolean)protected Session createSessionProxy(Session session)
session - the Hibernate Session to create a proxy for
Session.close(),
prepareQuery(org.hibernate.Query),
prepareCriteria(org.hibernate.Criteria)
public Object get(Class entityClass,
Serializable id)
throws DataAccessException
HibernateOperationsnull if not found.
This method is a thin wrapper around
Session.get(Class, java.io.Serializable) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
get in interface HibernateOperationsentityClass - a persistent classid - the identifier of the persistent instance
null if not found
DataAccessException - in case of Hibernate errorsSession.get(Class, java.io.Serializable)
public Object get(Class entityClass,
Serializable id,
LockMode lockMode)
throws DataAccessException
HibernateOperationsnull if not found.
Obtains the specified lock mode if the instance exists.
This method is a thin wrapper around
Session.get(Class, java.io.Serializable, LockMode) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
get in interface HibernateOperationsentityClass - a persistent classid - the identifier of the persistent instancelockMode - the lock mode to obtain
null if not found
DataAccessException - in case of Hibernate errorsSession.get(Class, java.io.Serializable, org.hibernate.LockMode)
public Object get(String entityName,
Serializable id)
throws DataAccessException
HibernateOperationsnull if not found.
This method is a thin wrapper around
Session.get(String, java.io.Serializable) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
get in interface HibernateOperationsentityName - the name of a persistent entityid - the identifier of the persistent instance
null if not found
DataAccessException - in case of Hibernate errorsSession.get(Class, java.io.Serializable)
public Object get(String entityName,
Serializable id,
LockMode lockMode)
throws DataAccessException
HibernateOperationsnull if not found.
Obtains the specified lock mode if the instance exists.
This method is a thin wrapper around
Session.get(String, java.io.Serializable, LockMode) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
get in interface HibernateOperationsentityName - the name of a persistent entityid - the identifier of the persistent instancelockMode - the lock mode to obtain
null if not found
DataAccessException - in case of Hibernate errorsSession.get(Class, java.io.Serializable, org.hibernate.LockMode)
public Object load(Class entityClass,
Serializable id)
throws DataAccessException
HibernateOperationsThis method is a thin wrapper around
Session.load(Class, java.io.Serializable) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
load in interface HibernateOperationsentityClass - a persistent classid - the identifier of the persistent instance
ObjectRetrievalFailureException - if not found
DataAccessException - in case of Hibernate errorsSession.load(Class, java.io.Serializable)
public Object load(Class entityClass,
Serializable id,
LockMode lockMode)
throws DataAccessException
HibernateOperationsThis method is a thin wrapper around
Session.load(Class, java.io.Serializable, LockMode) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
load in interface HibernateOperationsentityClass - a persistent classid - the identifier of the persistent instancelockMode - the lock mode to obtain
ObjectRetrievalFailureException - if not found
DataAccessException - in case of Hibernate errorsSession.load(Class, java.io.Serializable)
public Object load(String entityName,
Serializable id)
throws DataAccessException
HibernateOperationsThis method is a thin wrapper around
Session.load(String, java.io.Serializable) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
load in interface HibernateOperationsentityName - the name of a persistent entityid - the identifier of the persistent instance
ObjectRetrievalFailureException - if not found
DataAccessException - in case of Hibernate errorsSession.load(Class, java.io.Serializable)
public Object load(String entityName,
Serializable id,
LockMode lockMode)
throws DataAccessException
HibernateOperationsObtains the specified lock mode if the instance exists.
This method is a thin wrapper around
Session.load(String, java.io.Serializable, LockMode) for convenience.
For an explanation of the exact semantics of this method, please do refer to
the Hibernate API documentation in the first instance.
load in interface HibernateOperationsentityName - the name of a persistent entityid - the identifier of the persistent instancelockMode - the lock mode to obtain
ObjectRetrievalFailureException - if not found
DataAccessException - in case of Hibernate errorsSession.load(Class, java.io.Serializable)
public List loadAll(Class entityClass)
throws DataAccessException
HibernateOperations