| java.lang.Object org.springframework.orm.hibernate3.HibernateAccessor org.springframework.orm.hibernate3.HibernateTemplate
HibernateTemplate | public class HibernateTemplate extends HibernateAccessor implements HibernateOperations(Code) | | Helper class that simplifies Hibernate data access code. Automatically
converts HibernateExceptions into DataAccessExceptions, following the
org.springframework.dao exception hierarchy.
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.
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
org.hibernate.SessionFactory.getCurrentSession .
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 as well
as its capability to fall back to 'auto-commit' style behavior when used outside
of transactions. Note that HibernateTemplate will perform its own Session
management, not participating in a custom Hibernate CurrentSessionContext
unless you explicitly switch
HibernateTemplate.setAllowCreate "allowCreate" to "false".
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 .
author: Juergen Hoeller since: 1.2 See Also: HibernateTemplate.setSessionFactory See Also: HibernateCallback See Also: org.hibernate.Session See Also: LocalSessionFactoryBean See Also: HibernateTransactionManager See Also: org.springframework.transaction.jta.JtaTransactionManager See Also: org.springframework.orm.hibernate3.support.OpenSessionInViewFilter See Also: org.springframework.orm.hibernate3.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) Apply the given name parameter to the given Query object. | public int | bulkUpdate(String queryString) | public int | bulkUpdate(String queryString, Object value) | public int | bulkUpdate(String queryString, Object[] values) | 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/MANUAL . | 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 void | deleteAll(Collection entities) | public Filter | enableFilter(String filterName) | 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[] values) | public List | findByCriteria(DetachedCriteria criteria) | public List | findByCriteria(DetachedCriteria criteria, int firstResult, int maxResults) | public List | findByExample(Object exampleEntity) | public List | findByExample(String entityName, Object exampleEntity) | public List | findByExample(Object exampleEntity, int firstResult, int maxResults) | public List | findByExample(String entityName, Object exampleEntity, int firstResult, int maxResults) | public List | findByNamedParam(String queryString, String paramName, Object value) | public List | findByNamedParam(String queryString, String[] paramNames, Object[] values) | public List | findByNamedQuery(String queryName) | public List | findByNamedQuery(String queryName, Object value) | public List | findByNamedQuery(String queryName, Object[] values) | public List | findByNamedQueryAndNamedParam(String queryName, String paramName, Object value) | public List | findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) | 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 Object | get(String entityName, Serializable id) | public Object | get(String entityName, 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[] values) | public Object | load(Class entityClass, Serializable id) | public Object | load(Class entityClass, Serializable id, LockMode lockMode) | public Object | load(String entityName, Serializable id) | public Object | load(String entityName, Serializable id, LockMode lockMode) | public void | load(Object entity, Serializable id) | public List | loadAll(Class entityClass) | public void | lock(Object entity, LockMode lockMode) | public void | lock(String entityName, Object entity, LockMode lockMode) | public Object | merge(Object entity) | public Object | merge(String entityName, Object entity) | public void | persist(Object entity) | public void | persist(String entityName, Object entity) | 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 void | replicate(String entityName, Object entity, ReplicationMode replicationMode) | public Serializable | save(Object entity) | public Serializable | save(String entityName, Object entity) | public void | saveOrUpdate(Object entity) | public void | saveOrUpdate(String entityName, Object entity) | public void | saveOrUpdateAll(Collection entities) | public void | setAllowCreate(boolean allowCreate) Set if a new
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 .
| 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) | public void | update(String entityName, Object entity) | public void | update(String entityName, 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) 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 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: org.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.
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.
NOTE: As of Spring 2.5, switching allowCreate
to false will delegate to Hibernate's
org.hibernate.SessionFactory.getCurrentSession method,
which - with Spring-based setup - will by default delegate to Spring's
SessionFactoryUtils.getSession(sessionFactory, false) .
This mode also allows for custom Hibernate CurrentSessionContext strategies
to be plugged in, whereas allowCreate set to true
will always use a Spring-managed Hibernate Session.
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: org.hibernate.Query.setCacheable See Also: org.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: org.hibernate.Query.setCacheRegion See Also: org.hibernate.Criteria.setCacheRegion |
|
|