Save This Page
Home » spring-framework-2.5.4 » org.springframework » orm » hibernate3 » [javadoc | source]
org.springframework.orm.hibernate3
public class: HibernateTemplate [javadoc | source]
java.lang.Object
   org.springframework.orm.hibernate3.HibernateAccessor
      org.springframework.orm.hibernate3.HibernateTemplate

All Implemented Interfaces:
    HibernateOperations, BeanFactoryAware, 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: 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 "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.

Fields inherited from org.springframework.orm.hibernate3.HibernateAccessor:
FLUSH_NEVER,  FLUSH_AUTO,  FLUSH_EAGER,  FLUSH_COMMIT,  FLUSH_ALWAYS,  logger
Constructor:
 public HibernateTemplate() 
 public HibernateTemplate(SessionFactory sessionFactory) 
    Create a new HibernateTemplate instance.
    Parameters:
    sessionFactory - SessionFactory to create Sessions
 public HibernateTemplate(SessionFactory sessionFactory,
    boolean allowCreate) 
    Create a new HibernateTemplate instance.
    Parameters:
    sessionFactory - SessionFactory to create Sessions
    allowCreate - if a non-transactional Session should be created when no transactional Session can be found for the current thread
Method from org.springframework.orm.hibernate3.HibernateTemplate Summary:
applyNamedParameterToQuery,   bulkUpdate,   bulkUpdate,   bulkUpdate,   checkWriteOperationAllowed,   clear,   closeIterator,   contains,   createSessionProxy,   delete,   delete,   delete,   delete,   deleteAll,   doExecute,   enableFilter,   evict,   execute,   execute,   executeFind,   executeWithNativeSession,   executeWithNewSession,   find,   find,   find,   findByCriteria,   findByCriteria,   findByExample,   findByExample,   findByExample,   findByExample,   findByNamedParam,   findByNamedParam,   findByNamedQuery,   findByNamedQuery,   findByNamedQuery,   findByNamedQueryAndNamedParam,   findByNamedQueryAndNamedParam,   findByNamedQueryAndValueBean,   findByValueBean,   flush,   get,   get,   get,   get,   getFetchSize,   getMaxResults,   getQueryCacheRegion,   getSession,   initialize,   isAllowCreate,   isAlwaysUseNewSession,   isCacheQueries,   isCheckWriteOperations,   isExposeNativeSession,   iterate,   iterate,   iterate,   load,   load,   load,   load,   load,   loadAll,   lock,   lock,   merge,   merge,   persist,   persist,   prepareCriteria,   prepareQuery,   refresh,   refresh,   replicate,   replicate,   save,   save,   saveOrUpdate,   saveOrUpdate,   saveOrUpdateAll,   setAllowCreate,   setAlwaysUseNewSession,   setCacheQueries,   setCheckWriteOperations,   setExposeNativeSession,   setFetchSize,   setMaxResults,   setQueryCacheRegion,   update,   update,   update,   update
Methods from org.springframework.orm.hibernate3.HibernateAccessor:
afterPropertiesSet,   applyFlushMode,   convertHibernateAccessException,   convertJdbcAccessException,   convertJdbcAccessException,   disableFilters,   enableFilters,   flushIfNecessary,   getDefaultJdbcExceptionTranslator,   getEntityInterceptor,   getFilterNames,   getFlushMode,   getJdbcExceptionTranslator,   getSessionFactory,   setBeanFactory,   setEntityInterceptor,   setEntityInterceptorBeanName,   setFilterName,   setFilterNames,   setFlushMode,   setFlushModeName,   setJdbcExceptionTranslator,   setSessionFactory
Methods from java.lang.Object:
equals,   getClass,   hashCode,   notify,   notifyAll,   toString,   wait,   wait,   wait
Method from org.springframework.orm.hibernate3.HibernateTemplate Detail:
 protected  void applyNamedParameterToQuery(Query queryObject,
    String paramName,
    Object value) throws HibernateException 
    Apply the given name parameter to the given Query object.
 public int bulkUpdate(String queryString) throws DataAccessException 
 public int bulkUpdate(String queryString,
    Object value) throws DataAccessException 
 public int bulkUpdate(String queryString,
    Object[] values) throws DataAccessException 
 protected  void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException 
    Check whether write operations are allowed on the given Session.

    Default implementation throws an InvalidDataAccessApiUsageException in case of FlushMode.NEVER/MANUAL. Can be overridden in subclasses.

 public  void clear() throws DataAccessException 
 public  void closeIterator(Iterator it) throws DataAccessException 
 public boolean contains(Object entity) throws DataAccessException 
 protected Session createSessionProxy(Session session) 
    Create a close-suppressing proxy for the given Hibernate Session. The proxy also prepares returned Query and Criteria objects.
 public  void delete(Object entity) throws DataAccessException 
 public  void delete(Object entity,
    LockMode lockMode) throws DataAccessException 
 public  void delete(String entityName,
    Object entity) throws DataAccessException 
 public  void delete(String entityName,
    Object entity,
    LockMode lockMode) throws DataAccessException 
 public  void deleteAll(Collection entities) throws DataAccessException 
 protected Object doExecute(HibernateCallback action,
    boolean enforceNewSession,
    boolean enforceNativeSession) throws DataAccessException 
    Execute the action specified by the given action object within a Session.
 public Filter enableFilter(String filterName) throws IllegalStateException 
 public  void evict(Object entity) throws DataAccessException 
 public Object execute(HibernateCallback action) throws DataAccessException 
 public Object execute(HibernateCallback action,
    boolean enforceNativeSession) throws DataAccessException 
Deprecated! as - of Spring 2.5, in favor of #executeWithNativeSession

    Execute the action specified by the given action object within a Session.
 public List executeFind(HibernateCallback action) throws DataAccessException 
 public Object executeWithNativeSession(HibernateCallback action) 
 public Object executeWithNewSession(HibernateCallback action) 
 public List find(String queryString) throws DataAccessException 
 public List find(String queryString,
    Object value) throws DataAccessException 
 public List find(String queryString,
    Object[] values) throws DataAccessException 
 public List findByCriteria(DetachedCriteria criteria) throws DataAccessException 
 public List findByCriteria(DetachedCriteria criteria,
    int firstResult,
    int maxResults) throws DataAccessException 
 public List findByExample(Object exampleEntity) throws DataAccessException 
 public List findByExample(String entityName,
    Object exampleEntity) throws DataAccessException 
 public List findByExample(Object exampleEntity,
    int firstResult,
    int maxResults) throws DataAccessException 
 public List findByExample(String entityName,
    Object exampleEntity,
    int firstResult,
    int maxResults) throws DataAccessException 
 public List findByNamedParam(String queryString,
    String paramName,
    Object value) throws DataAccessException 
 public List findByNamedParam(String queryString,
    String[] paramNames,
    Object[] values) throws DataAccessException 
 public List findByNamedQuery(String queryName) throws DataAccessException 
 public List findByNamedQuery(String queryName,
    Object value) throws DataAccessException 
 public List findByNamedQuery(String queryName,
    Object[] values) throws DataAccessException 
 public List findByNamedQueryAndNamedParam(String queryName,
    String paramName,
    Object value) throws DataAccessException 
 public List findByNamedQueryAndNamedParam(String queryName,
    String[] paramNames,
    Object[] values) throws DataAccessException 
 public List findByNamedQueryAndValueBean(String queryName,
    Object valueBean) throws DataAccessException 
 public List findByValueBean(String queryString,
    Object valueBean) throws DataAccessException 
 public  void flush() throws DataAccessException 
 public Object get(Class entityClass,
    Serializable id) throws DataAccessException 
 public Object get(String entityName,
    Serializable id) throws DataAccessException 
 public Object get(Class entityClass,
    Serializable id,
    LockMode lockMode) throws DataAccessException 
 public Object get(String entityName,
    Serializable id,
    LockMode lockMode) throws DataAccessException 
 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.

    Returns a new Session in case of "alwaysUseNewSession" (using the same JDBC Connection as a transactional Session, if applicable), a pre-bound Session in case of "allowCreate" turned off, and a pre-bound or new Session otherwise (new only if no transactional or otherwise pre-bound Session exists).

 public  void initialize(Object proxy) throws DataAccessException 
 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) throws DataAccessException 
 public Iterator iterate(String queryString,
    Object value) throws DataAccessException 
 public Iterator iterate(String queryString,
    Object[] values) throws DataAccessException 
 public Object load(Class entityClass,
    Serializable id) throws DataAccessException 
 public Object load(String entityName,
    Serializable id) throws DataAccessException 
 public  void load(Object entity,
    Serializable id) throws DataAccessException 
 public Object load(Class entityClass,
    Serializable id,
    LockMode lockMode) throws DataAccessException 
 public Object load(String entityName,
    Serializable id,
    LockMode lockMode) throws DataAccessException 
 public List loadAll(Class entityClass) throws DataAccessException 
 public  void lock(Object entity,
    LockMode lockMode) throws DataAccessException 
 public  void lock(String entityName,
    Object entity,
    LockMode lockMode) throws DataAccessException 
 public Object merge(Object entity) throws DataAccessException 
 public Object merge(String entityName,
    Object entity) throws DataAccessException 
 public  void persist(Object entity) throws DataAccessException 
 public  void persist(String entityName,
    Object entity) throws DataAccessException 
 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) throws DataAccessException 
 public  void refresh(Object entity,
    LockMode lockMode) throws DataAccessException 
 public  void replicate(Object entity,
    ReplicationMode replicationMode) throws DataAccessException 
 public  void replicate(String entityName,
    Object entity,
    ReplicationMode replicationMode) throws DataAccessException 
 public Serializable save(Object entity) throws DataAccessException 
 public Serializable save(String entityName,
    Object entity) throws DataAccessException 
 public  void saveOrUpdate(Object entity) throws DataAccessException 
 public  void saveOrUpdate(String entityName,
    Object entity) throws DataAccessException 
 public  void saveOrUpdateAll(Collection entities) throws DataAccessException 
 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 . 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.

 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. 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.

 public  void setCacheQueries(boolean cacheQueries) 
    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.

 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. Turn this off to allow save/update/delete on a Session with flush mode NEVER.

 public  void setExposeNativeSession(boolean exposeNativeSession) 
    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.

 public  void setFetchSize(int fetchSize) 
    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.

 public  void setMaxResults(int maxResults) 
    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.

 public  void setQueryCacheRegion(String queryCacheRegion) 
    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.

 public  void update(Object entity) throws DataAccessException 
 public  void update(Object entity,
    LockMode lockMode) throws DataAccessException 
 public  void update(String entityName,
    Object entity) throws DataAccessException 
 public  void update(String entityName,
    Object entity,
    LockMode lockMode) throws DataAccessException