Top Description Inners Fields Constructors Methods
org.springframework.orm.hibernate5

public Class HibernateTemplate

extends Object
implements HibernateOperations, InitializingBean
Class Inheritance
All Implemented Interfaces
org.springframework.beans.factory.InitializingBean, org.springframework.orm.hibernate5.HibernateOperations
Imports
java.io.Serializable, java.lang.reflect.InvocationHandler, .InvocationTargetException, .Method, .Proxy, java.util.Collection, .Iterator, .List, jakarta.persistence.PersistenceException, org.apache.commons.logging.Log, .LogFactory, org.hibernate.Criteria, .Filter, .FlushMode, .Hibernate, .HibernateException, .LockMode, .LockOptions, .ReplicationMode, .Session, .SessionFactory, org.hibernate.criterion.DetachedCriteria, .Example, org.hibernate.query.Query, org.springframework.beans.factory.InitializingBean, org.springframework.dao.DataAccessException, .InvalidDataAccessApiUsageException, org.springframework.lang.Nullable, org.springframework.transaction.support.ResourceHolderSupport, .TransactionSynchronizationManager, org.springframework.util.Assert

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.

Author
Juergen Hoeller
Since
4.2
See Also
setSessionFactory, HibernateCallback, Session, LocalSessionFactoryBean, HibernateTransactionManager, org.springframework.orm.hibernate5.support.OpenSessionInViewFilter, org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
HibernateTemplate.CloseSuppressingInvocationHandler

Invocation handler that suppresses close calls on Hibernate Sessions.

Field Summary

Modifier and TypeField and Description
private boolean
private boolean
private boolean
private int
private String[]
protected final Log
private int
private String
private SessionFactory
sessionFactory

References Deprecated SessionFactory is deprecated or references (maybe indirectly) at least one deprecated element.

Constructor Summary

AccessConstructor and Description
public
HibernateTemplate()

Create a new HibernateTemplate instance.

public
HibernateTemplate(SessionFactory
the SessionFactory to create Sessions with
sessionFactory
)
References Deprecated SessionFactory is deprecated or references (maybe indirectly) at least one deprecated element.

Create a new HibernateTemplate instance.

Method Summary

Modifier and TypeMethod and Description
public void
afterPropertiesSet()

Implements org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

Invoked by the containing BeanFactory after it has set all bean properties and satisfied BeanFactoryAware, ApplicationContextAware etc.

This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.

protected void
applyNamedParameterToQuery(Query<?>
the Query object
queryObject
,
String
the name of the parameter
paramName
,
Object
the value of the parameter
value
)
References Deprecated Query is deprecated or references (maybe indirectly) at least one deprecated element.

Apply the given name parameter to the given Query object.

public int
bulkUpdate(String
an update/delete query expressed in Hibernate's query language
queryString
,
Object...
the values of the parameters
values
)

Implements org.springframework.orm.hibernate5.HibernateOperations.bulkUpdate.

Deprecated

Update/delete all objects according to the given query, binding a number of values to "?" parameters in the query string.

protected void
checkWriteOperationAllowed(Session
current Hibernate Session
session
)
References Deprecated Session is deprecated or references (maybe indirectly) at least one deprecated element.

Check whether write operations are allowed on the given Session.

public void
clear()

Implements org.springframework.orm.hibernate5.HibernateOperations.clear.

Remove all objects from the org.hibernate.Session cache, and cancel all pending saves, updates and deletes.

public void
closeIterator(Iterator<?>
the Iterator to close
it
)

Implements org.springframework.orm.hibernate5.HibernateOperations.closeIterator.

Deprecated

Immediately close an Iterator created by any of the various iterate(..) operations, instead of waiting until the session is closed or disconnected.

public boolean
contains(Object
the persistence instance to check
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.contains.

Check whether the given object is in the Session cache.

protected Session

Returns:

the Session proxy
createSessionProxy
(Session
the Hibernate Session to create a proxy for
session
)
References Deprecated Session is deprecated or references (maybe indirectly) at least one deprecated element.

Create a close-suppressing proxy for the given Hibernate Session.

public void
delete(Object
the persistent instance to delete
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.delete.

Delete the given persistent instance.

public void
delete(Object
the persistent instance to delete
entity
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.delete.

Delete the given persistent instance.

public void
delete(String
the name of the persistent entity
entityName
,
Object
the persistent instance to delete
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.delete.

Delete the given persistent instance.

public void
delete(String
the name of the persistent entity
entityName
,
Object
the persistent instance to delete
entity
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.delete.

Delete the given persistent instance.

public void
deleteAll(Collection<?>
the persistent instances to delete
entities
)

Implements org.springframework.orm.hibernate5.HibernateOperations.deleteAll.

Delete all given persistent instances.

protected void
disableFilters(Session
the current Hibernate Session
session
)
References Deprecated Session is deprecated or references (maybe indirectly) at least one deprecated element.

Disable the specified filters on the given Session.

protected <T> T

Returns:

a result object returned by the action, or null
doExecute
(HibernateCallback<T>
callback object that specifies the Hibernate action
action
,
boolean
whether to enforce exposure of the native Hibernate Session to callback code
enforceNativeSession
)

Execute the action specified by the given action object within a Session.

public Filter
enableFilter(String
the name of the filter
filterName
)

Implements org.springframework.orm.hibernate5.HibernateOperations.enableFilter.

Return an enabled Hibernate Filter for the given filter name.

protected void
enableFilters(Session
the current Hibernate Session
session
)
References Deprecated Session is deprecated or references (maybe indirectly) at least one deprecated element.

Enable the specified filters on the given Session.

public void
evict(Object
the persistent instance to evict
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.evict.

Remove the given object from the org.hibernate.Session cache.

public <T> T
execute(HibernateCallback<T>
callback object that specifies the Hibernate action
action
)

Implements org.springframework.orm.hibernate5.HibernateOperations.execute.

Execute the action specified by the given action object within a org.hibernate.Session.

public <T> T

Returns:

a result object returned by the action, or null
executeWithNativeSession
(HibernateCallback<T>
callback object that specifies the Hibernate action
action
)

Execute the action specified by the given action object within a native Session.

public List<?>
find(String
a query expressed in Hibernate's query language
queryString
,
Object...
the values of the parameters
values
)

Implements org.springframework.orm.hibernate5.HibernateOperations.find.

Deprecated

Execute an HQL query, binding a number of values to "?" parameters in the query string.

public List<?>
findByCriteria(DetachedCriteria
the detached Hibernate criteria object.

Note

Do not reuse criteria objects! They need to recreated per execution, due to the suboptimal design of Hibernate's criteria facility.

criteria
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByCriteria.

Execute a query based on a given Hibernate criteria object.

public List<?>
findByCriteria(DetachedCriteria
the detached Hibernate criteria object.

Note

Do not reuse criteria objects! They need to recreated per execution, due to the suboptimal design of Hibernate's criteria facility.

criteria
,
int
the index of the first result object to be retrieved (numbered from 0)
firstResult
,
int
the maximum number of result objects to retrieve (or <=0 for no limit)
maxResults
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByCriteria.

Execute a query based on the given Hibernate criteria object.

public <T> List<T>
findByExample(T
an instance of the desired entity, serving as example for "query-by-example"
exampleEntity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByExample.

Execute a query based on the given example entity object.

public <T> List<T>
findByExample(String
the name of the persistent entity
entityName
,
T
an instance of the desired entity, serving as example for "query-by-example"
exampleEntity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByExample.

Execute a query based on the given example entity object.

public <T> List<T>
findByExample(T
an instance of the desired entity, serving as example for "query-by-example"
exampleEntity
,
int
the index of the first result object to be retrieved (numbered from 0)
firstResult
,
int
the maximum number of result objects to retrieve (or <=0 for no limit)
maxResults
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByExample.

Execute a query based on a given example entity object.

public <T> List<T>
findByExample(String
the name of the persistent entity
entityName
,
T
an instance of the desired entity, serving as example for "query-by-example"
exampleEntity
,
int
the index of the first result object to be retrieved (numbered from 0)
firstResult
,
int
the maximum number of result objects to retrieve (or <=0 for no limit)
maxResults
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByExample.

Execute a query based on a given example entity object.

public List<?>
findByNamedParam(String
a query expressed in Hibernate's query language
queryString
,
String
the name of the parameter
paramName
,
Object
the value of the parameter
value
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByNamedParam.

Deprecated

Execute an HQL query, binding one value to a ":" named parameter in the query string.

public List<?>
findByNamedParam(String
a query expressed in Hibernate's query language
queryString
,
String[]
the names of the parameters
paramNames
,
Object[]
the values of the parameters
values
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByNamedParam.

Deprecated

Execute an HQL query, binding a number of values to ":" named parameters in the query string.

public List<?>
findByNamedQuery(String
the name of a Hibernate query in a mapping file
queryName
,
Object...
the values of the parameters
values
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByNamedQuery.

Deprecated

Execute a named query binding a number of values to "?" parameters in the query string.

public List<?>
findByNamedQueryAndNamedParam(String
the name of a Hibernate query in a mapping file
queryName
,
String
the name of parameter
paramName
,
Object
the value of the parameter
value
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByNamedQueryAndNamedParam.

Deprecated

Execute a named query, binding one value to a ":" named parameter in the query string.

public List<?>
findByNamedQueryAndNamedParam(String
the name of a Hibernate query in a mapping file
queryName
,
String[]
the names of the parameters
paramNames
,
Object[]
the values of the parameters
values
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByNamedQueryAndNamedParam.

Deprecated

Execute a named query, binding a number of values to ":" named parameters in the query string.

public List<?>
findByNamedQueryAndValueBean(String
the name of a Hibernate query in a mapping file
queryName
,
Object
the values of the parameters
valueBean
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByNamedQueryAndValueBean.

Deprecated

Execute a named query, binding the properties of the given bean to ":" named parameters in the query string.

public List<?>
findByValueBean(String
a query expressed in Hibernate's query language
queryString
,
Object
the values of the parameters
valueBean
)

Implements org.springframework.orm.hibernate5.HibernateOperations.findByValueBean.

Deprecated

Execute an HQL query, binding the properties of the given bean to named parameters in the query string.

public void
flush()

Implements org.springframework.orm.hibernate5.HibernateOperations.flush.

Flush all pending saves, updates and deletes to the database.

public <T> T
get(Class<T>
a persistent class
entityClass
,
Serializable
the identifier of the persistent instance
id
)

Implements org.springframework.orm.hibernate5.HibernateOperations.get.

Return the persistent instance of the given entity class with the given identifier, or null if not found.

public <T> T
get(Class<T>
a persistent class
entityClass
,
Serializable
the identifier of the persistent instance
id
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.get.

Return the persistent instance of the given entity class with the given identifier, or null if not found.

public Object
get(String
the name of the persistent entity
entityName
,
Serializable
the identifier of the persistent instance
id
)

Implements org.springframework.orm.hibernate5.HibernateOperations.get.

Return the persistent instance of the given entity class with the given identifier, or null if not found.

public Object
get(String
the name of the persistent entity
entityName
,
Serializable
the identifier of the persistent instance
id
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.get.

Return the persistent instance of the given entity class with the given identifier, or null if not found.

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()
References Deprecated SessionFactory is deprecated or references (maybe indirectly) at least one deprecated element.

Return the Hibernate SessionFactory that should be used to create Hibernate Sessions.

public void
initialize(Object
a proxy for a persistent object or a persistent collection
proxy
)

Implements org.springframework.orm.hibernate5.HibernateOperations.initialize.

Force initialization of a Hibernate proxy or persistent collection.

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
a query expressed in Hibernate's query language
queryString
,
Object...
the values of the parameters
values
)

Implements org.springframework.orm.hibernate5.HibernateOperations.iterate.

Deprecated

Execute a query for persistent instances, binding a number of values to "?" parameters in the query string.

public <T> T
load(Class<T>
a persistent class
entityClass
,
Serializable
the identifier of the persistent instance
id
)

Implements org.springframework.orm.hibernate5.HibernateOperations.load.

Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found.

public <T> T
load(Class<T>
a persistent class
entityClass
,
Serializable
the identifier of the persistent instance
id
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.load.

Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found.

public Object
load(String
the name of the persistent entity
entityName
,
Serializable
the identifier of the persistent instance
id
)

Implements org.springframework.orm.hibernate5.HibernateOperations.load.

Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found.

public Object
load(String
the name of the persistent entity
entityName
,
Serializable
the identifier of the persistent instance
id
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.load.

Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found.

public void
load(Object
the object (of the target class) to load into
entity
,
Serializable
the identifier of the persistent instance
id
)

Implements org.springframework.orm.hibernate5.HibernateOperations.load.

Load the persistent instance with the given identifier into the given object, throwing an exception if not found.

public <T> List<T>
loadAll(Class<T>
a persistent class
entityClass
)

Implements org.springframework.orm.hibernate5.HibernateOperations.loadAll.

Return all persistent instances of the given entity class.

public void
lock(Object
the persistent instance to lock
entity
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.lock.

Obtain the specified lock level upon the given object, implicitly checking whether the corresponding database entry still exists.

public void
lock(String
the name of the persistent entity
entityName
,
Object
the persistent instance to lock
entity
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.lock.

Obtain the specified lock level upon the given object, implicitly checking whether the corresponding database entry still exists.

public <T> T
merge(T
the object to merge with the corresponding persistence instance
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.merge.

Copy the state of the given object onto the persistent object with the same identifier.

public <T> T
merge(String
the name of the persistent entity
entityName
,
T
the object to merge with the corresponding persistence instance
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.merge.

Copy the state of the given object onto the persistent object with the same identifier.

private static <T> T
nonNull(T result)

protected final SessionFactory

Returns:

the SessionFactory (never null)
obtainSessionFactory
()
References Deprecated SessionFactory is deprecated or references (maybe indirectly) at least one deprecated element.

Obtain the SessionFactory for actual use.

public void
persist(Object
the persistent instance to persist
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.persist.

Persist the given transient instance.

public void
persist(String
the name of the persistent entity
entityName
,
Object
the persistent instance to persist
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.persist.

Persist the given transient instance.

protected void
prepareCriteria(Criteria
the Criteria object to prepare
criteria
)

Prepare the given Criteria object, applying cache settings and/or a transaction timeout.

protected void
prepareQuery(Query<?>
the Query object to prepare
queryObject
)
References Deprecated Query is deprecated or references (maybe indirectly) at least one deprecated element.

Prepare the given Query object, applying cache settings and/or a transaction timeout.

public void
refresh(Object
the persistent instance to re-read
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.refresh.

Re-read the state of the given persistent instance.

public void
refresh(Object
the persistent instance to re-read
entity
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.refresh.

Re-read the state of the given persistent instance.

public void
replicate(Object
the persistent object to replicate
entity
,
ReplicationMode
the Hibernate ReplicationMode
replicationMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.replicate.

Persist the state of the given detached instance according to the given replication mode, reusing the current identifier value.

public void
replicate(String
the name of the persistent entity
entityName
,
Object
the persistent object to replicate
entity
,
ReplicationMode
the Hibernate ReplicationMode
replicationMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.replicate.

Persist the state of the given detached instance according to the given replication mode, reusing the current identifier value.

public Serializable
save(Object
the transient instance to persist
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.save.

Persist the given transient instance.

public Serializable
save(String
the name of the persistent entity
entityName
,
Object
the transient instance to persist
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.save.

Persist the given transient instance.

public void
saveOrUpdate(Object
the persistent instance to save or update (to be associated with the Hibernate Session)
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.saveOrUpdate.

Save or update the given persistent instance, according to its id (matching the configured "unsaved-value"?).

public void
saveOrUpdate(String
the name of the persistent entity
entityName
,
Object
the persistent instance to save or update (to be associated with the Hibernate Session)
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.saveOrUpdate.

Save or update the given persistent instance, according to its id (matching the configured "unsaved-value"?).

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)
References Deprecated SessionFactory is deprecated or references (maybe indirectly) at least one deprecated element.

Set the Hibernate SessionFactory that should be used to create Hibernate Sessions.

public void
update(Object
the persistent instance to update
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.update.

Update the given persistent instance, associating it with the current Hibernate org.hibernate.Session.

public void
update(Object
the persistent instance to update
entity
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.update.

Update the given persistent instance, associating it with the current Hibernate org.hibernate.Session.

public void
update(String
the name of the persistent entity
entityName
,
Object
the persistent instance to update
entity
)

Implements org.springframework.orm.hibernate5.HibernateOperations.update.

Update the given persistent instance, associating it with the current Hibernate org.hibernate.Session.

public void
update(String
the name of the persistent entity
entityName
,
Object
the persistent instance to update
entity
,
LockMode
the lock mode to obtain
lockMode
)

Implements org.springframework.orm.hibernate5.HibernateOperations.update.

Update the given persistent instance, associating it with the current Hibernate org.hibernate.Session.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait