public class HibernateTemplate extends Object implements HibernateOperations, InitializingBean
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: Hibernate access code can also be coded against the native Hibernate
Session. Hence, for newly started projects, consider adopting the standard
Hibernate style of coding against SessionFactory.getCurrentSession.
Alternatively, use execute(HibernateCallback) with Java 8 lambda code blocks
against the callback-provided Session which results in elegant code as well,
decoupled from the Hibernate Session lifecycle. The remaining operations on this
HibernateTemplate are deprecated in the meantime and primarily exist as a migration
helper for older Hibernate 3.x/4.x data access code in existing applications.
| Modifiers | Name | Description |
|---|---|---|
protected org.apache.commons.logging.Log |
logger |
| Constructor and description |
|---|
HibernateTemplate()Create a new HibernateTemplate instance. |
HibernateTemplate(SessionFactory sessionFactory)Create a new HibernateTemplate instance. |
| Type Params | Return Type | Name and description |
|---|---|---|
|
public void |
afterPropertiesSet() |
|
protected void |
applyNamedParameterToQuery(Query<?> queryObject, String paramName, Object value)Apply the given name parameter to the given Query object. |
|
public int |
bulkUpdate(String queryString, Object values) |
|
protected void |
checkWriteOperationAllowed(Session session)Check whether write operations are allowed on the given Session. |
|
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 |
delete(String entityName, Object entity) |
|
public void |
delete(String entityName, Object entity, LockMode lockMode) |
|
public void |
deleteAll(Collection<?> entities) |
|
protected void |
disableFilters(Session session)Disable the specified filters on the given Session. |
<T> |
protected T |
doExecute(HibernateCallback<T> action, boolean enforceNativeSession)Execute the action specified by the given action object within a Session. |
|
public Filter |
enableFilter(String filterName) |
|
protected void |
enableFilters(Session session)Enable the specified filters on the given Session. |
|
public void |
evict(Object entity) |
<T> |
public T |
execute(HibernateCallback<T> action) |
<T> |
public T |
executeWithNativeSession(HibernateCallback<T> action)Execute the action specified by the given action object within a native Session. |
|
public List<?> |
find(String queryString, Object values) |
|
public List<?> |
findByCriteria(DetachedCriteria criteria) |
|
public List<?> |
findByCriteria(DetachedCriteria criteria, int firstResult, int maxResults) |
<T> |
public List<T> |
findByExample(T exampleEntity) |
<T> |
public List<T> |
findByExample(String entityName, T exampleEntity) |
<T> |
public List<T> |
findByExample(T exampleEntity, int firstResult, int maxResults) |
<T> |
public List<T> |
findByExample(String entityName, T 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, 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() |
<T> |
public T |
get(Class<T> entityClass, Serializable id) |
<T> |
public T |
get(Class<T> 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 String[] |
getFilterNames()Return the names of Hibernate filters to be activated, if any. |
|
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. |
|
public SessionFactory |
getSessionFactory()Return the Hibernate SessionFactory that should be used to create Hibernate Sessions. |
|
public void |
initialize(Object proxy) |
|
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, Object values) |
<T> |
public T |
load(Class<T> entityClass, Serializable id) |
<T> |
public T |
load(Class<T> 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) |
<T> |
public List<T> |
loadAll(Class<T> entityClass) |
|
public void |
lock(Object entity, LockMode lockMode) |
|
public void |
lock(String entityName, Object entity, LockMode lockMode) |
<T> |
public T |
merge(T entity) |
<T> |
public T |
merge(String entityName, T entity) |
|
protected final SessionFactory |
obtainSessionFactory()Obtain the SessionFactory for actual use. |
|
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 |
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). |
|
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 |
setFilterNames(String filterNames)Set one or more names of Hibernate filters to be activated for all Sessions that this accessor works with. |
|
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 |
setSessionFactory(SessionFactory sessionFactory)Set the Hibernate SessionFactory that should be used to create Hibernate Sessions. |
|
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) |
Create a new HibernateTemplate instance.
Create a new HibernateTemplate instance.
sessionFactory - the SessionFactory to create Sessions withApply the given name parameter to the given Query object.
queryObject - the Query objectparamName - the name of the parametervalue - the value of the parameterCheck whether write operations are allowed on the given Session.
Default implementation throws an InvalidDataAccessApiUsageException in
case of FlushMode.MANUAL. Can be overridden in subclasses.
session - current Hibernate SessionCreate a close-suppressing proxy for the given Hibernate Session. The proxy also prepares returned Query and Criteria objects.
session - the Hibernate Session to create a proxy forDisable the specified filters on the given Session.
session - the current Hibernate SessionExecute the action specified by the given action object within a Session.
action - callback object that specifies the Hibernate actionenforceNativeSession - whether to enforce exposure of the native
Hibernate Session to callback codenullEnable the specified filters on the given Session.
session - the current Hibernate SessionExecute the action specified by the given action object within a native Session.
This execute variant overrides the template-wide "exposeNativeSession" setting.
action - callback object that specifies the Hibernate actionnullReturn the fetch size specified for this HibernateTemplate.
Return the names of Hibernate filters to be activated, if any.
Return the maximum number of rows specified for this HibernateTemplate.
Return the name of the cache region for queries executed by this template.
Return the Hibernate SessionFactory that should be used to create Hibernate Sessions.
Return whether to cache all queries executed by this template.
Return whether to check that the Hibernate Session is not in read-only mode in case of write operations (save/update/delete).
Return whether to expose the native Hibernate Session to HibernateCallback code, or rather a Session proxy.
Obtain the SessionFactory for actual use.
null)Prepare the given Criteria object, applying cache settings and/or a transaction timeout.
criteria - the Criteria object to preparePrepare the given Query object, applying cache settings and/or a transaction timeout.
queryObject - the Query object to prepareSet 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.
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. Turn this off to allow save/update/delete on a Session with flush mode MANUAL.
Set whether to expose the native Hibernate Session to HibernateCallback code.
Default is "false": a Session proxy will be returned, suppressing
close calls and automatically applying query cache
settings and transaction timeouts.
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.
Set one or more names of Hibernate filters to be activated for all Sessions that this accessor works with.
Each of those filters will be enabled at the beginning of each operation and correspondingly disabled at the end of the operation. This will work for newly opened Sessions as well as for existing Sessions (for example, within a transaction).
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.
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.
Set the Hibernate SessionFactory that should be used to create Hibernate Sessions.