Helper class that simplifies Hibernate data access code. Automatically
converts HibernateExceptions into DataAccessExceptions, following the
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.
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".
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.
| Method from org.springframework.orm.hibernate3.HibernateTemplate Detail: |
protected void applyNamedParameterToQuery(Query queryObject,
String paramName,
Object value) throws HibernateException {
if (value instanceof Collection) {
queryObject.setParameterList(paramName, (Collection) value);
}
else if (value instanceof Object[]) {
queryObject.setParameterList(paramName, (Object[]) value);
}
else {
queryObject.setParameter(paramName, value);
}
}
Apply the given name parameter to the given Query object. |
public int bulkUpdate(String queryString) throws DataAccessException {
return bulkUpdate(queryString, (Object[]) null);
}
|
public int bulkUpdate(String queryString,
Object value) throws DataAccessException {
return bulkUpdate(queryString, new Object[] {value});
}
|
public int bulkUpdate(String queryString,
Object[] values) throws DataAccessException {
Integer updateCount = (Integer) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return new Integer(queryObject.executeUpdate());
}
});
return updateCount.intValue();
}
|
protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException {
if (isCheckWriteOperations() && getFlushMode() != FLUSH_EAGER &&
session.getFlushMode().lessThan(FlushMode.COMMIT)) {
throw new InvalidDataAccessApiUsageException(
"Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): "+
"Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.");
}
}
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 {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
session.clear();
return null;
}
});
}
|
public void closeIterator(Iterator it) throws DataAccessException {
try {
Hibernate.close(it);
}
catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
}
}
|
public boolean contains(Object entity) throws DataAccessException {
Boolean result = (Boolean) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
return (session.contains(entity) ? Boolean.TRUE : Boolean.FALSE);
}
});
return result.booleanValue();
}
|
protected Session createSessionProxy(Session session) {
Class[] sessionIfcs = null;
Class mainIfc = (session instanceof org.hibernate.classic.Session ?
org.hibernate.classic.Session.class : Session.class);
if (session instanceof EventSource) {
sessionIfcs = new Class[] {mainIfc, EventSource.class};
}
else if (session instanceof SessionImplementor) {
sessionIfcs = new Class[] {mainIfc, SessionImplementor.class};
}
else {
sessionIfcs = new Class[] {mainIfc};
}
return (Session) Proxy.newProxyInstance(
getClass().getClassLoader(), sessionIfcs,
new CloseSuppressingInvocationHandler(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 {
delete(entity, null);
}
|
public void delete(Object entity,
LockMode lockMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
if (lockMode != null) {
session.lock(entity, lockMode);
}
session.delete(entity);
return null;
}
});
}
|
public void delete(String entityName,
Object entity) throws DataAccessException {
delete(entityName, entity, null);
}
|
public void delete(String entityName,
Object entity,
LockMode lockMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
if (lockMode != null) {
session.lock(entityName, entity, lockMode);
}
session.delete(entityName, entity);
return null;
}
});
}
|
public void deleteAll(Collection entities) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
for (Iterator it = entities.iterator(); it.hasNext();) {
session.delete(it.next());
}
return null;
}
});
}
|
protected Object doExecute(HibernateCallback action,
boolean enforceNewSession,
boolean enforceNativeSession) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Session session = (enforceNewSession ?
SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()) : getSession());
boolean existingTransaction = (!enforceNewSession &&
(!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory())));
if (existingTransaction) {
logger.debug("Found thread-bound Session for HibernateTemplate");
}
FlushMode previousFlushMode = null;
try {
previousFlushMode = applyFlushMode(session, existingTransaction);
enableFilters(session);
Session sessionToExpose =
(enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
Object result = action.doInHibernate(sessionToExpose);
flushIfNecessary(session, existingTransaction);
return result;
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
catch (SQLException ex) {
throw convertJdbcAccessException(ex);
}
catch (RuntimeException ex) {
// Callback code threw application exception...
throw ex;
}
finally {
if (existingTransaction) {
logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
else {
// Never use deferred close for an explicitly new Session.
if (isAlwaysUseNewSession()) {
SessionFactoryUtils.closeSession(session);
}
else {
SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
}
}
}
}
Execute the action specified by the given action object within a Session. |
public Filter enableFilter(String filterName) throws IllegalStateException {
Session session = SessionFactoryUtils.getSession(getSessionFactory(), false);
Filter filter = session.getEnabledFilter(filterName);
if (filter == null) {
filter = session.enableFilter(filterName);
}
return filter;
}
|
public void evict(Object entity) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
session.evict(entity);
return null;
}
});
}
|
public Object execute(HibernateCallback action) throws DataAccessException {
return doExecute(action, false, false);
}
|
public Object execute(HibernateCallback action,
boolean enforceNativeSession) throws DataAccessException {
return doExecute(action, false, enforceNativeSession);
} 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 {
Object result = doExecute(action, false, false);
if (result != null && !(result instanceof List)) {
throw new InvalidDataAccessApiUsageException(
"Result object returned from HibernateCallback isn't a List: [" + result + "]");
}
return (List) result;
}
|
public Object executeWithNativeSession(HibernateCallback action) {
return doExecute(action, false, true);
}
|
public Object executeWithNewSession(HibernateCallback action) {
return doExecute(action, true, false);
}
|
public List find(String queryString) throws DataAccessException {
return find(queryString, (Object[]) null);
}
|
public List find(String queryString,
Object value) throws DataAccessException {
return find(queryString, new Object[] {value});
}
|
public List find(String queryString,
Object[] values) throws DataAccessException {
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject.list();
}
});
}
|
public List findByCriteria(DetachedCriteria criteria) throws DataAccessException {
return findByCriteria(criteria, -1, -1);
}
|
public List findByCriteria(DetachedCriteria criteria,
int firstResult,
int maxResults) throws DataAccessException {
Assert.notNull(criteria, "DetachedCriteria must not be null");
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria executableCriteria = criteria.getExecutableCriteria(session);
prepareCriteria(executableCriteria);
if (firstResult >= 0) {
executableCriteria.setFirstResult(firstResult);
}
if (maxResults > 0) {
executableCriteria.setMaxResults(maxResults);
}
return executableCriteria.list();
}
});
}
|
public List findByExample(Object exampleEntity) throws DataAccessException {
return findByExample(null, exampleEntity, -1, -1);
}
|
public List findByExample(String entityName,
Object exampleEntity) throws DataAccessException {
return findByExample(entityName, exampleEntity, -1, -1);
}
|
public List findByExample(Object exampleEntity,
int firstResult,
int maxResults) throws DataAccessException {
return findByExample(null, exampleEntity, firstResult, maxResults);
}
|
public List findByExample(String entityName,
Object exampleEntity,
int firstResult,
int maxResults) throws DataAccessException {
Assert.notNull(exampleEntity, "Example entity must not be null");
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria executableCriteria = (entityName != null ?
session.createCriteria(entityName) : session.createCriteria(exampleEntity.getClass()));
executableCriteria.add(Example.create(exampleEntity));
prepareCriteria(executableCriteria);
if (firstResult >= 0) {
executableCriteria.setFirstResult(firstResult);
}
if (maxResults > 0) {
executableCriteria.setMaxResults(maxResults);
}
return executableCriteria.list();
}
});
}
|
public List findByNamedParam(String queryString,
String paramName,
Object value) throws DataAccessException {
return findByNamedParam(queryString, new String[] {paramName}, new Object[] {value});
}
|
public List findByNamedParam(String queryString,
String[] paramNames,
Object[] values) throws DataAccessException {
if (paramNames.length != values.length) {
throw new IllegalArgumentException("Length of paramNames array must match length of values array");
}
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
}
}
return queryObject.list();
}
});
}
|
public List findByNamedQuery(String queryName) throws DataAccessException {
return findByNamedQuery(queryName, (Object[]) null);
}
|
public List findByNamedQuery(String queryName,
Object value) throws DataAccessException {
return findByNamedQuery(queryName, new Object[] {value});
}
|
public List findByNamedQuery(String queryName,
Object[] values) throws DataAccessException {
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.getNamedQuery(queryName);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject.list();
}
});
}
|
public List findByNamedQueryAndNamedParam(String queryName,
String paramName,
Object value) throws DataAccessException {
return findByNamedQueryAndNamedParam(queryName, new String[] {paramName}, new Object[] {value});
}
|
public List findByNamedQueryAndNamedParam(String queryName,
String[] paramNames,
Object[] values) throws DataAccessException {
if (paramNames != null && values != null && paramNames.length != values.length) {
throw new IllegalArgumentException("Length of paramNames array must match length of values array");
}
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.getNamedQuery(queryName);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
}
}
return queryObject.list();
}
});
}
|
public List findByNamedQueryAndValueBean(String queryName,
Object valueBean) throws DataAccessException {
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.getNamedQuery(queryName);
prepareQuery(queryObject);
queryObject.setProperties(valueBean);
return queryObject.list();
}
});
}
|
public List findByValueBean(String queryString,
Object valueBean) throws DataAccessException {
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
queryObject.setProperties(valueBean);
return queryObject.list();
}
});
}
|
public void flush() throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
session.flush();
return null;
}
});
}
|
public Object get(Class entityClass,
Serializable id) throws DataAccessException {
return get(entityClass, id, null);
}
|
public Object get(String entityName,
Serializable id) throws DataAccessException {
return get(entityName, id, null);
}
|
public Object get(Class entityClass,
Serializable id,
LockMode lockMode) throws DataAccessException {
return executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
if (lockMode != null) {
return session.get(entityClass, id, lockMode);
}
else {
return session.get(entityClass, id);
}
}
});
}
|
public Object get(String entityName,
Serializable id,
LockMode lockMode) throws DataAccessException {
return executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
if (lockMode != null) {
return session.get(entityName, id, lockMode);
}
else {
return session.get(entityName, id);
}
}
});
}
|
public int getFetchSize() {
return this.fetchSize;
}
Return the fetch size specified for this HibernateTemplate. |
public int getMaxResults() {
return this.maxResults;
}
Return the maximum number of rows specified for this HibernateTemplate. |
public String getQueryCacheRegion() {
return this.queryCacheRegion;
}
Return the name of the cache region for queries executed by this template. |
protected Session getSession() {
if (isAlwaysUseNewSession()) {
return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
}
else if (isAllowCreate()) {
return SessionFactoryUtils.getSession(
getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
}
else {
try {
return getSessionFactory().getCurrentSession();
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex);
}
}
}
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 {
try {
Hibernate.initialize(proxy);
}
catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
}
}
|
public boolean isAllowCreate() {
return this.allowCreate;
}
Return if a new Session should be created if no thread-bound found. |
public boolean isAlwaysUseNewSession() {
return this.alwaysUseNewSession;
}
Return whether to always use a new Hibernate Session for this template. |
public boolean isCacheQueries() {
return this.cacheQueries;
}
Return whether to cache all queries executed by this template. |
public boolean isCheckWriteOperations() {
return this.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 isExposeNativeSession() {
return this.exposeNativeSession;
}
Return whether to expose the native Hibernate Session to
HibernateCallback code, or rather a Session proxy. |
public Iterator iterate(String queryString) throws DataAccessException {
return iterate(queryString, (Object[]) null);
}
|
public Iterator iterate(String queryString,
Object value) throws DataAccessException {
return iterate(queryString, new Object[] {value});
}
|
public Iterator iterate(String queryString,
Object[] values) throws DataAccessException {
return (Iterator) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject.iterate();
}
});
}
|
public Object load(Class entityClass,
Serializable id) throws DataAccessException {
return load(entityClass, id, null);
}
|
public Object load(String entityName,
Serializable id) throws DataAccessException {
return load(entityName, id, null);
}
|
public void load(Object entity,
Serializable id) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
session.load(entity, id);
return null;
}
});
}
|
public Object load(Class entityClass,
Serializable id,
LockMode lockMode) throws DataAccessException {
return executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
if (lockMode != null) {
return session.load(entityClass, id, lockMode);
}
else {
return session.load(entityClass, id);
}
}
});
}
|
public Object load(String entityName,
Serializable id,
LockMode lockMode) throws DataAccessException {
return executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
if (lockMode != null) {
return session.load(entityName, id, lockMode);
}
else {
return session.load(entityName, id);
}
}
});
}
|
public List loadAll(Class entityClass) throws DataAccessException {
return (List) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria criteria = session.createCriteria(entityClass);
prepareCriteria(criteria);
return criteria.list();
}
});
}
|
public void lock(Object entity,
LockMode lockMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
session.lock(entity, lockMode);
return null;
}
});
}
|
public void lock(String entityName,
Object entity,
LockMode lockMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
session.lock(entityName, entity, lockMode);
return null;
}
});
}
|
public Object merge(Object entity) throws DataAccessException {
return executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
return session.merge(entity);
}
});
}
|
public Object merge(String entityName,
Object entity) throws DataAccessException {
return executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
return session.merge(entityName, entity);
}
});
}
|
public void persist(Object entity) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.persist(entity);
return null;
}
});
}
|
public void persist(String entityName,
Object entity) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.persist(entityName, entity);
return null;
}
});
}
|
protected void prepareCriteria(Criteria criteria) {
if (isCacheQueries()) {
criteria.setCacheable(true);
if (getQueryCacheRegion() != null) {
criteria.setCacheRegion(getQueryCacheRegion());
}
}
if (getFetchSize() > 0) {
criteria.setFetchSize(getFetchSize());
}
if (getMaxResults() > 0) {
criteria.setMaxResults(getMaxResults());
}
SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory());
}
Prepare the given Criteria object, applying cache settings and/or
a transaction timeout. |
protected void prepareQuery(Query queryObject) {
if (isCacheQueries()) {
queryObject.setCacheable(true);
if (getQueryCacheRegion() != null) {
queryObject.setCacheRegion(getQueryCacheRegion());
}
}
if (getFetchSize() > 0) {
queryObject.setFetchSize(getFetchSize());
}
if (getMaxResults() > 0) {
queryObject.setMaxResults(getMaxResults());
}
SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory());
}
Prepare the given Query object, applying cache settings and/or
a transaction timeout. |
public void refresh(Object entity) throws DataAccessException {
refresh(entity, null);
}
|
public void refresh(Object entity,
LockMode lockMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
if (lockMode != null) {
session.refresh(entity, lockMode);
}
else {
session.refresh(entity);
}
return null;
}
});
}
|
public void replicate(Object entity,
ReplicationMode replicationMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.replicate(entity, replicationMode);
return null;
}
});
}
|
public void replicate(String entityName,
Object entity,
ReplicationMode replicationMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.replicate(entityName, entity, replicationMode);
return null;
}
});
}
|
public Serializable save(Object entity) throws DataAccessException {
return (Serializable) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
return session.save(entity);
}
});
}
|
public Serializable save(String entityName,
Object entity) throws DataAccessException {
return (Serializable) executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
return session.save(entityName, entity);
}
});
}
|
public void saveOrUpdate(Object entity) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.saveOrUpdate(entity);
return null;
}
});
}
|
public void saveOrUpdate(String entityName,
Object entity) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.saveOrUpdate(entityName, entity);
return null;
}
});
}
|
public void saveOrUpdateAll(Collection entities) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
for (Iterator it = entities.iterator(); it.hasNext();) {
session.saveOrUpdate(it.next());
}
return null;
}
});
}
|
public void setAllowCreate(boolean allowCreate) {
this.allowCreate = 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) {
this.alwaysUseNewSession = 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) {
this.cacheQueries = 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) {
this.checkWriteOperations = 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) {
this.exposeNativeSession = 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) {
this.fetchSize = 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) {
this.maxResults = 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) {
this.queryCacheRegion = 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 {
update(entity, null);
}
|
public void update(Object entity,
LockMode lockMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.update(entity);
if (lockMode != null) {
session.lock(entity, lockMode);
}
return null;
}
});
}
|
public void update(String entityName,
Object entity) throws DataAccessException {
update(entityName, entity, null);
}
|
public void update(String entityName,
Object entity,
LockMode lockMode) throws DataAccessException {
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
session.update(entityName, entity);
if (lockMode != null) {
session.lock(entity, lockMode);
}
return null;
}
});
}
|