| java.lang.Object org.springframework.orm.hibernate.HibernateAccessor org.springframework.orm.hibernate.HibernateTemplate
HibernateTemplate | public class HibernateTemplate extends HibernateAccessor implements HibernateOperations(Code) | | Helper class that simplifies Hibernate data access code, and converts
checked HibernateExceptions into unchecked DataAccessExceptions,
following the org.springframework.dao exception hierarchy.
Uses the same SQLExceptionTranslator mechanism as JdbcTemplate.
Typically used to implement data access or business logic services that
use Hibernate within their implementation but are Hibernate-agnostic in their
interface. The latter or code calling the latter only have to deal with
domain objects, query objects, and org.springframework.dao exceptions.
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
Hibernate Session API (through SessionFactoryUtils.getSession() ).
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 .
Note: Spring's Hibernate support in this package requires Hibernate 2.1.
Dedicated Hibernate3 support can be found in a separate package:
org.springframework.orm.hibernate3 .
author: Juergen Hoeller since: 02.05.2003 See Also: HibernateTemplate.setSessionFactory See Also: HibernateTemplate.setJdbcExceptionTranslator See Also: HibernateCallback See Also: net.sf.hibernate.Session See Also: HibernateInterceptor See Also: LocalSessionFactoryBean See Also: org.springframework.jndi.JndiObjectFactoryBean See Also: org.springframework.jdbc.support.SQLExceptionTranslator See Also: HibernateTransactionManager See Also: org.springframework.transaction.jta.JtaTransactionManager See Also: org.springframework.orm.hibernate.support.OpenSessionInViewFilter See Also: org.springframework.orm.hibernate.support.OpenSessionInViewInterceptor |
Constructor Summary | |
public | HibernateTemplate() Create a new HibernateTemplate instance. | public | HibernateTemplate(SessionFactory sessionFactory) Create a new HibernateTemplate instance. | public | HibernateTemplate(SessionFactory sessionFactory, boolean allowCreate) Create a new HibernateTemplate instance. |
Method Summary | |
protected void | applyNamedParameterToQuery(Query queryObject, String paramName, Object value, Type type) Apply the given name parameter to the given Query object. | protected void | checkWriteOperationAllowed(Session session) Check whether write operations are allowed on the given Session.
Default implementation throws an InvalidDataAccessApiUsageException
in case of FlushMode.NEVER . | public void | clear() | public void | closeIterator(Iterator it) | public boolean | contains(Object entity) | protected Session | createSessionProxy(Session session) Create a close-suppressing proxy for the given Hibernate Session. | public void | delete(Object entity) | public void | delete(Object entity, LockMode lockMode) | public int | delete(String queryString) | public int | delete(String queryString, Object value, Type type) | public int | delete(String queryString, Object[] values, Type[] types) | public void | deleteAll(Collection entities) | public void | evict(Object entity) | public Object | execute(HibernateCallback action) | public Object | execute(HibernateCallback action, boolean exposeNativeSession) Execute the action specified by the given action object within a Session. | public List | executeFind(HibernateCallback action) | public List | find(String queryString) | public List | find(String queryString, Object value) | public List | find(String queryString, Object value, Type type) | public List | find(String queryString, Object[] values) | public List | find(String queryString, Object[] values, Type[] types) | public List | findByNamedParam(String queryString, String paramName, Object value) | public List | findByNamedParam(String queryString, String paramName, Object value, Type type) | public List | findByNamedParam(String queryString, String[] paramNames, Object[] values) | public List | findByNamedParam(String queryString, String[] paramNames, Object[] values, Type[] types) | public List | findByNamedQuery(String queryName) | public List | findByNamedQuery(String queryName, Object value) | public List | findByNamedQuery(String queryName, Object value, Type type) | public List | findByNamedQuery(String queryName, Object[] values) | public List | findByNamedQuery(String queryName, Object[] values, Type[] types) | public List | findByNamedQueryAndNamedParam(String queryName, String paramName, Object value) | public List | findByNamedQueryAndNamedParam(String queryName, String paramName, Object value, Type type) | public List | findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) | public List | findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values, Type[] types) | public List | findByNamedQueryAndValueBean(String queryName, Object valueBean) | public List | findByValueBean(String queryString, Object valueBean) | public void | flush() | public Object | get(Class entityClass, Serializable id) | public Object | get(Class entityClass, Serializable id, LockMode lockMode) | public int | getFetchSize() Return the fetch size specified for this HibernateTemplate. | public int | getMaxResults() Return the maximum number of rows specified for this HibernateTemplate. | public 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. | public void | initialize(Object proxy) | public boolean | isAllowCreate() Return if a new Session should be created if no thread-bound found. | public boolean | isAlwaysUseNewSession() Return whether to always use a new Hibernate Session for this template. | public boolean | isCacheQueries() Return whether to cache all queries executed by this template. | public boolean | isCheckWriteOperations() Return whether to check that the Hibernate Session is not in read-only
mode in case of write operations (save/update/delete). | public boolean | isExposeNativeSession() Return whether to expose the native Hibernate Session to HibernateCallback
code, or rather a Session proxy. | public Iterator | iterate(String queryString) | public Iterator | iterate(String queryString, Object value) | public Iterator | iterate(String queryString, Object value, Type type) | public Iterator | iterate(String queryString, Object[] values) | public Iterator | iterate(String queryString, Object[] values, Type[] types) | public Object | load(Class entityClass, Serializable id) | public Object | load(Class entityClass, Serializable id, LockMode lockMode) | public void | load(Object entity, Serializable id) | public List | loadAll(Class entityClass) | public void | lock(Object entity, LockMode lockMode) | 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. | public void | refresh(Object entity) | public void | refresh(Object entity, LockMode lockMode) | public void | replicate(Object entity, ReplicationMode replicationMode) | public Serializable | save(Object entity) | public void | save(Object entity, Serializable id) | public void | saveOrUpdate(Object entity) | public void | saveOrUpdateAll(Collection entities) | public Object | saveOrUpdateCopy(Object entity) | public void | setAllowCreate(boolean allowCreate) Set if a new Session should be created when no transactional Session
can be found for the current thread. | public void | setAlwaysUseNewSession(boolean alwaysUseNewSession) Set whether to always use a new Hibernate Session for this template.
Default is "false"; if activated, all operations on this template will
work on a new Hibernate Session even in case of a pre-bound Session
(for example, within a transaction or OpenSessionInViewFilter).
Within a transaction, a new Hibernate Session used by this template
will participate in the transaction through using the same JDBC
Connection. | public void | setCacheQueries(boolean cacheQueries) Set whether to cache all queries executed by this template. | public 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).
Default is "true", for fail-fast behavior when attempting write operations
within a read-only transaction. | public void | setExposeNativeSession(boolean exposeNativeSession) Set whether to expose the native Hibernate Session to HibernateCallback
code. | public void | setFetchSize(int fetchSize) Set the fetch size for this HibernateTemplate. | public void | setMaxResults(int maxResults) Set the maximum number of rows for this HibernateTemplate. | public void | setQueryCacheRegion(String queryCacheRegion) Set the name of the cache region for queries executed by this template. | public void | update(Object entity) | public void | update(Object entity, LockMode lockMode) |
HibernateTemplate | public HibernateTemplate()(Code) | | Create a new HibernateTemplate instance.
|
HibernateTemplate | public HibernateTemplate(SessionFactory sessionFactory)(Code) | | Create a new HibernateTemplate instance.
Parameters: sessionFactory - SessionFactory to create Sessions |
HibernateTemplate | public HibernateTemplate(SessionFactory sessionFactory, boolean allowCreate)(Code) | | Create a new HibernateTemplate instance.
Parameters: sessionFactory - SessionFactory to create Sessions Parameters: allowCreate - if a non-transactional Session should be created when notransactional Session can be found for the current thread |
applyNamedParameterToQuery | protected void applyNamedParameterToQuery(Query queryObject, String paramName, Object value, Type type) throws HibernateException(Code) | | Apply the given name parameter to the given Query object.
Parameters: queryObject - the Query object Parameters: paramName - the name of the parameter Parameters: value - the value of the parameter Parameters: type - Hibernate type of the parameter (or null if none specified) throws: HibernateException - if thrown by the Query object |
createSessionProxy | protected Session createSessionProxy(Session session)(Code) | | Create a close-suppressing proxy for the given Hibernate Session.
The proxy also prepares returned Query and Criteria objects.
Parameters: session - the Hibernate Session to create a proxy for the Session proxy See Also: net.sf.hibernate.Session.close See Also: HibernateTemplate.prepareQuery See Also: HibernateTemplate.prepareCriteria |
execute | public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException(Code) | | Execute the action specified by the given action object within a Session.
Parameters: action - callback object that specifies the Hibernate action Parameters: exposeNativeSession - whether to expose the native Hibernate Sessionto callback code a result object returned by the action, or null throws: org.springframework.dao.DataAccessException - in case of Hibernate errors |
getFetchSize | public int getFetchSize()(Code) | | Return the fetch size specified for this HibernateTemplate.
|
getMaxResults | public int getMaxResults()(Code) | | Return the maximum number of rows specified for this HibernateTemplate.
|
getQueryCacheRegion | public String getQueryCacheRegion()(Code) | | Return the name of the cache region for queries executed by this template.
|
isAllowCreate | public boolean isAllowCreate()(Code) | | Return if a new Session should be created if no thread-bound found.
|
isAlwaysUseNewSession | public boolean isAlwaysUseNewSession()(Code) | | Return whether to always use a new Hibernate Session for this template.
|
isCacheQueries | public boolean isCacheQueries()(Code) | | Return whether to cache all queries executed by this template.
|
isCheckWriteOperations | public boolean isCheckWriteOperations()(Code) | | Return whether to check that the Hibernate Session is not in read-only
mode in case of write operations (save/update/delete).
|
isExposeNativeSession | public boolean isExposeNativeSession()(Code) | | Return whether to expose the native Hibernate Session to HibernateCallback
code, or rather a Session proxy.
|
setAllowCreate | public void setAllowCreate(boolean allowCreate)(Code) | | Set if a new Session should be created when no transactional Session
can be found for the current thread.
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 found, which needs to be closed at the end of the operation.
If false, an IllegalStateException will get thrown in this case.
See Also: SessionFactoryUtils.getSession(SessionFactoryboolean) |
setAlwaysUseNewSession | public void setAlwaysUseNewSession(boolean alwaysUseNewSession)(Code) | | Set whether to always use a new Hibernate Session for this template.
Default is "false"; if activated, all operations on this template will
work on a new Hibernate Session even in case of a pre-bound Session
(for example, within a transaction or OpenSessionInViewFilter).
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.
|
setCacheQueries | public void setCacheQueries(boolean cacheQueries)(Code) | | Set whether to cache all queries executed by this template.
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.
See Also: HibernateTemplate.setQueryCacheRegion See Also: net.sf.hibernate.Query.setCacheable See Also: net.sf.hibernate.Criteria.setCacheable |
setFetchSize | public void setFetchSize(int fetchSize)(Code) | | Set the fetch size for this HibernateTemplate. This is important for processing
large result sets: Setting this higher than the default value will increase
processing speed at the cost of memory consumption; setting this lower can
avoid transferring row data that will never be read by the application.
Default is 0, indicating to use the JDBC driver's default.
|
setMaxResults | public void setMaxResults(int maxResults)(Code) | | Set the maximum number of rows for this HibernateTemplate. This is important
for processing subsets of large result sets, avoiding to read and hold
the entire result set in the database or in the JDBC driver if we're
never interested in the entire result in the first place (for example,
when performing searches that might return a large number of matches).
Default is 0, indicating to use the JDBC driver's default.
|
setQueryCacheRegion | public void setQueryCacheRegion(String queryCacheRegion)(Code) | | Set the name of the cache region for queries executed by this template.
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.
See Also: HibernateTemplate.setCacheQueries See Also: net.sf.hibernate.Query.setCacheRegion See Also: net.sf.hibernate.Criteria.setCacheRegion |
|
|