Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.hibernate4;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Filter;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.ReplicationMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
/**
* Helper class that simplifies Hibernate data access code. Automatically
* converts HibernateExceptions into DataAccessExceptions, following the
* {@code org.springframework.dao} exception hierarchy.
*
*
The central method is {@code execute}, supporting Hibernate access code
* implementing the {@link 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 in plain Hibernate style.
* Hence, for newly started projects, consider adopting the standard Hibernate
* style of coding data access objects instead, based on
* {@link org.hibernate.SessionFactory#getCurrentSession()}.
* This HibernateTemplate primarily exists as a migration helper for Hibernate 3
* based data access code, to benefit from bug fixes in Hibernate 4.x.
*
* @author Juergen Hoeller
* @since 4.0.1
* @see #setSessionFactory
* @see HibernateCallback
* @see org.hibernate.Session
* @see LocalSessionFactoryBean
* @see HibernateTransactionManager
* @see org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
* @see org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor
*/
public class HibernateTemplate implements HibernateOperations, InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
private SessionFactory sessionFactory;
private String[] filterNames;
private boolean exposeNativeSession = false;
private boolean checkWriteOperations = true;
private boolean cacheQueries = false;
private String queryCacheRegion;
private int fetchSize = 0;
private int maxResults = 0;
/**
* Create a new HibernateTemplate instance.
*/
public HibernateTemplate() {
}
/**
* Create a new HibernateTemplate instance.
* @param sessionFactory the SessionFactory to create Sessions with
*/
public HibernateTemplate(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
afterPropertiesSet();
}
/**
* Set the Hibernate SessionFactory that should be used to create
* Hibernate Sessions.
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* Return the Hibernate SessionFactory that should be used to create
* Hibernate Sessions.
*/
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
/**
* 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).
* @see #enableFilters(org.hibernate.Session)
* @see org.hibernate.Session#enableFilter(String)
*/
public void setFilterNames(String... filterNames) {
this.filterNames = filterNames;
}
/**
* Return the names of Hibernate filters to be activated, if any.
*/
public String[] getFilterNames() {
return this.filterNames;
}
/**
* Set whether to expose the native Hibernate Session to
* HibernateCallback code.
*
Default is "false": a Session proxy will be returned, suppressing
* {@code close} calls and automatically applying query cache
* settings and transaction timeouts.
* @see HibernateCallback
* @see org.hibernate.Session
* @see #setCacheQueries
* @see #setQueryCacheRegion
* @see #prepareQuery
* @see #prepareCriteria
*/
public void setExposeNativeSession(boolean exposeNativeSession) {
this.exposeNativeSession = exposeNativeSession;
}
/**
* Return whether to expose the native Hibernate Session to
* HibernateCallback code, or rather a Session proxy.
*/
public boolean isExposeNativeSession() {
return this.exposeNativeSession;
}
/**
* 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.
* @see #checkWriteOperationAllowed
* @see org.springframework.transaction.TransactionDefinition#isReadOnly
*/
public void setCheckWriteOperations(boolean checkWriteOperations) {
this.checkWriteOperations = checkWriteOperations;
}
/**
* Return whether to check that the Hibernate Session is not in read-only
* mode in case of write operations (save/update/delete).
*/
public boolean isCheckWriteOperations() {
return this.checkWriteOperations;
}
/**
* 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 #setQueryCacheRegion
* @see org.hibernate.Query#setCacheable
* @see org.hibernate.Criteria#setCacheable
*/
public void setCacheQueries(boolean cacheQueries) {
this.cacheQueries = cacheQueries;
}
/**
* Return whether to cache all queries executed by this template.
*/
public boolean isCacheQueries() {
return this.cacheQueries;
}
/**
* 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 #setCacheQueries
* @see org.hibernate.Query#setCacheRegion
* @see org.hibernate.Criteria#setCacheRegion
*/
public void setQueryCacheRegion(String queryCacheRegion) {
this.queryCacheRegion = queryCacheRegion;
}
/**
* Return the name of the cache region for queries executed by this template.
*/
public String getQueryCacheRegion() {
return this.queryCacheRegion;
}
/**
* 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 setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
}
/**
* Return the fetch size specified for this HibernateTemplate.
*/
public int getFetchSize() {
return this.fetchSize;
}
/**
* 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 setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
/**
* Return the maximum number of rows specified for this HibernateTemplate.
*/
public int getMaxResults() {
return this.maxResults;
}
@Override
public void afterPropertiesSet() {
if (getSessionFactory() == null) {
throw new IllegalArgumentException("Property 'sessionFactory' is required");
}
}
@Override
public T execute(HibernateCallback action) throws DataAccessException {
return doExecute(action, false);
}
/**
* Execute the action specified by the given action object within a
* native {@link org.hibernate.Session}.
*
This execute variant overrides the template-wide
* {@link #isExposeNativeSession() "exposeNativeSession"} setting.
* @param action callback object that specifies the Hibernate action
* @return a result object returned by the action, or {@code null}
* @throws org.springframework.dao.DataAccessException in case of Hibernate errors
*/
public T executeWithNativeSession(HibernateCallback action) {
return doExecute(action, true);
}
/**
* Execute the action specified by the given action object within a Session.
* @param action callback object that specifies the Hibernate action
* @param enforceNativeSession whether to enforce exposure of the native
* Hibernate Session to callback code
* @return a result object returned by the action, or {@code null}
* @throws org.springframework.dao.DataAccessException in case of Hibernate errors
*/
protected T doExecute(HibernateCallback action, boolean enforceNativeSession) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Session session = null;
boolean isNew = false;
try {
session = getSessionFactory().getCurrentSession();
}
catch (HibernateException ex) {
logger.debug("Could not retrieve pre-bound Hibernate session", ex);
}
if (session == null) {
session = getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
isNew = true;
}
try {
enableFilters(session);
Session sessionToExpose =
(enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
return action.doInHibernate(sessionToExpose);
}
catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
}
catch (RuntimeException ex) {
// Callback code threw application exception...
throw ex;
}
finally {
if (isNew) {
SessionFactoryUtils.closeSession(session);
}
else {
disableFilters(session);
}
}
}
/**
* Create a close-suppressing proxy for the given Hibernate Session.
* The proxy also prepares returned Query and Criteria objects.
* @param session the Hibernate Session to create a proxy for
* @return the Session proxy
* @see org.hibernate.Session#close()
* @see #prepareQuery
* @see #prepareCriteria
*/
protected Session createSessionProxy(Session session) {
return (Session) Proxy.newProxyInstance(
session.getClass().getClassLoader(), new Class[] {Session.class},
new CloseSuppressingInvocationHandler(session));
}
/**
* Enable the specified filters on the given Session.
* @param session the current Hibernate Session
* @see #setFilterNames
* @see org.hibernate.Session#enableFilter(String)
*/
protected void enableFilters(Session session) {
String[] filterNames = getFilterNames();
if (filterNames != null) {
for (String filterName : filterNames) {
session.enableFilter(filterName);
}
}
}
/**
* Disable the specified filters on the given Session.
* @param session the current Hibernate Session
* @see #setFilterNames
* @see org.hibernate.Session#disableFilter(String)
*/
protected void disableFilters(Session session) {
String[] filterNames = getFilterNames();
if (filterNames != null) {
for (String filterName : filterNames) {
session.disableFilter(filterName);
}
}
}
//-------------------------------------------------------------------------
// Convenience methods for loading individual objects
//-------------------------------------------------------------------------
@Override
public T get(Class entityClass, Serializable id) throws DataAccessException {
return get(entityClass, id, null);
}
@Override
public T get(final Class entityClass, final Serializable id, final LockMode lockMode)
throws DataAccessException {
return executeWithNativeSession(new HibernateCallback() {
@Override
@SuppressWarnings("unchecked")
public T doInHibernate(Session session) throws HibernateException {
if (lockMode != null) {
return (T) session.get(entityClass, id, new LockOptions(lockMode));
}
else {
return (T) session.get(entityClass, id);
}
}
});
}
@Override
public Object get(String entityName, Serializable id) throws DataAccessException {
return get(entityName, id, null);
}
@Override
public Object get(final String entityName, final Serializable id, final LockMode lockMode)
throws DataAccessException {
return executeWithNativeSession(new HibernateCallback