Class HibernateTemplate

java.lang.Object
org.springframework.orm.hibernate5.HibernateTemplate
All Implemented Interfaces:
InitializingBean, HibernateOperations

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.

Since:
4.2
Author:
Juergen Hoeller
See Also: