HibernateTemplate源码
- package org.springframework.orm.hibernate3;
- 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.sql.SQLException;
- import java.util.Collection;
- import java.util.Iterator;
- import java.util.List;
- 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.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.hibernate.engine.SessionImplementor;
- import org.hibernate.event.EventSource;
- import org.springframework.dao.DataAccessException;
- import org.springframework.dao.DataAccessResourceFailureException;
- import org.springframework.dao.InvalidDataAccessApiUsageException;
- import org.springframework.util.Assert;
- public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {
- private boolean allowCreate = true;
- private boolean alwaysUseNewSession = false;
- private boolean exposeNativeSession = false;
- private boolean checkWriteOperations = true;
- private boolean cacheQueries = false;
- private String queryCacheRegion;
- private int fetchSize = 0;
- private int maxResults = 0;
- public HibernateTemplate() {
- }
- public HibernateTemplate(SessionFactory sessionFactory) {
- setSessionFactory(sessionFactory);
- afterPropertiesSet();
- }
- public HibernateTemplate(SessionFactory sessionFactory, boolean allowCreate) {
- setSessionFactory(sessionFactory);
- setAllowCreate(allowCreate);
- afterPropertiesSet();
- }
- public void setAllowCreate(boolean allowCreate) {
- this.allowCreate = allowCreate;
- }
- public boolean isAllowCreate() {
- return this.allowCreate;
- }
- public void setAlwaysUseNewSession(boolean alwaysUseNewSession) {
- this.alwaysUseNewSession = alwaysUseNewSession;
- }
- public boolean isAlwaysUseNewSession() {
- return this.alwaysUseNewSession;
- }
- public void setExposeNativeSession(boolean exposeNativeSession) {
- this.exposeNativeSession = exposeNativeSession;
- }
- public boolean isExposeNativeSession() {
- return this.exposeNativeSession;
- }
- public void setCheckWriteOperations(boolean checkWriteOperations) {
- this.checkWriteOperations = checkWriteOperations;
- }
- public boolean isCheckWriteOperations() {
- return this.checkWriteOperations;
- }
- public void setCacheQueries(boolean cacheQueries) {
- this.cacheQueries = cacheQueries;
- }
- public boolean isCacheQueries() {
- return this.cacheQueries;
- }
- public void setQueryCacheRegion(String queryCacheRegion) {
- this.queryCacheRegion = queryCacheRegion;
- }
- public String getQueryCacheRegion() {
- return this.queryCacheRegion;
- }
- public void setFetchSize(int fetchSize) {
- this.fetchSize = fetchSize;
- }
- public int getFetchSize() {
- return this.fetchSize;
- }
- public void setMaxResults(int maxResults) {
- this.maxResults = maxResults;
- }
- public int getMaxResults() {
- return this.maxResults;
- }
- public Object execute(HibernateCallback action) throws DataAccessException {
- return doExecute(action, false, false);
- }
- 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 executeWithNewSession(HibernateCallback action) {
- return doExecute(action, true, false);
- }
- public Object executeWithNativeSession(HibernateCallback action) {
- return doExecute(action, false, true);
- }
- public Object execute(HibernateCallback action, boolean enforceNativeSession) throws DataAccessException {
- return doExecute(action, false, enforceNativeSession);
- }
- 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());
- }
- }
- }
- }
- 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);
- }
- }
- }
- 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));
- }
- //-------------------------------------------------------------------------
- // Convenience methods for loading individual objects
- //-------------------------------------------------------------------------
- public Object get(Class entityClass, Serializable id) throws DataAccessException {
- return get(entityClass, id, null);
- }
- public Object get(final Class entityClass, final Serializable id, final 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) throws DataAccessException {
- return get(entityName, id, null);
- }
- public Object get(final String entityName, final Serializable id, final 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 Object load(Class entityClass, Serializable id) throws DataAccessException {
- return load(entityClass, id, null);
- }
- public Object load(final Class entityClass, final Serializable id, final 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) throws DataAccessException {
- return load(entityName, id, null);
- }
- public Object load(final String entityName, final Serializable id, final 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(final 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 load(final Object entity, final Serializable id) throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- session.load(entity, id);
- return null;
- }
- });
- }
- public void refresh(final Object entity) throws DataAccessException {
- refresh(entity, null);
- }
- public void refresh(final Object entity, final 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 boolean contains(final 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();
- }
- public void evict(final Object entity) throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- session.evict(entity);
- return null;
- }
- });
- }
- public void initialize(Object proxy) throws DataAccessException {
- try {
- Hibernate.initialize(proxy);
- }
- catch (HibernateException ex) {
- throw SessionFactoryUtils.convertHibernateAccessException(ex);
- }
- }
- 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;
- }
- //-------------------------------------------------------------------------
- // Convenience methods for storing individual objects
- //-------------------------------------------------------------------------
- public void lock(final Object entity, final LockMode lockMode) throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- session.lock(entity, lockMode);
- return null;
- }
- });
- }
- public void lock(final String entityName, final Object entity, final LockMode lockMode)
- throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- session.lock(entityName, entity, lockMode);
- return null;
- }
- });
- }
- public Serializable save(final 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(final String entityName, final 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 update(Object entity) throws DataAccessException {
- update(entity, null);
- }
- public void update(final Object entity, final 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(final String entityName, final Object entity, final 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;
- }
- });
- }
- public void saveOrUpdate(final Object entity) throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- session.saveOrUpdate(entity);
- return null;
- }
- });
- }
- public void saveOrUpdate(final String entityName, final 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(final 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 replicate(final Object entity, final 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(final String entityName, final Object entity, final ReplicationMode replicationMode)
- throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- session.replicate(entityName, entity, replicationMode);
- return null;
- }
- });
- }
- public void persist(final Object entity) throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- session.persist(entity);
- return null;
- }
- });
- }
- public void persist(final String entityName, final Object entity) throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- session.persist(entityName, entity);
- return null;
- }
- });
- }
- public Object merge(final Object entity) throws DataAccessException {
- return executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- return session.merge(entity);
- }
- });
- }
- public Object merge(final String entityName, final Object entity) throws DataAccessException {
- return executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- return session.merge(entityName, entity);
- }
- });
- }
- public void delete(Object entity) throws DataAccessException {
- delete(entity, null);
- }
- public void delete(final Object entity, final 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(final String entityName, final Object entity, final 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(final 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;
- }
- });
- }
- public void flush() throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- session.flush();
- return null;
- }
- });
- }
- public void clear() throws DataAccessException {
- executeWithNativeSession(new HibernateCallback() {
- public Object doInHibernate(Session session) {
- session.clear();
- return null;
- }
- });
- }
- //-------------------------------------------------------------------------
- // Convenience finder methods for HQL strings
- //-------------------------------------------------------------------------
- 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(final String queryString, final 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 findByNamedParam(String queryString, String paramName, Object value)
- throws DataAccessException {
- return findByNamedParam(queryString, new String[] {paramName}, new Object[] {value});
- }
- public List findByNamedParam(final String queryString, final String[] paramNames, final 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 findByValueBean(final String queryString, final 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();
- }
- });
- }
- //-------------------------------------------------------------------------
- // Convenience finder methods for named queries
- //-------------------------------------------------------------------------
- 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(final String queryName, final 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(
- final String queryName, final String[] paramNames, final 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(final String queryName, final 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();
- }
- });
- }
- //-------------------------------------------------------------------------
- // Convenience finder methods for detached criteria
- //-------------------------------------------------------------------------
- public List findByCriteria(DetachedCriteria criteria) throws DataAccessException {
- return findByCriteria(criteria, -1, -1);
- }
- public List findByCriteria(final DetachedCriteria criteria, final int firstResult, final 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(
- final String entityName, final Object exampleEntity, final int firstResult, final 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();
- }
- });
- }
- //-------------------------------------------------------------------------
- // Convenience query methods for iteration and bulk updates/deletes
- //-------------------------------------------------------------------------
- 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(final String queryString, final 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 void closeIterator(Iterator it) throws DataAccessException {
- try {
- Hibernate.close(it);
- }
- catch (HibernateException ex) {
- throw SessionFactoryUtils.convertHibernateAccessException(ex);
- }
- }
- 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(final String queryString, final 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();
- }
- //-------------------------------------------------------------------------
- // Helper methods used by the operations above
- //-------------------------------------------------------------------------
- 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.");
- }
- }
- 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());
- }
- 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());
- }
- 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);
- }
- }
- private class CloseSuppressingInvocationHandler implements InvocationHandler {
- private final Session target;
- public CloseSuppressingInvocationHandler(Session target) {
- this.target = target;
- }
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- // Invocation on Session interface coming in...
- if (method.getName().equals("equals")) {
- // Only consider equal when proxies are identical.
- return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
- }
- else if (method.getName().equals("hashCode")) {
- // Use hashCode of Session proxy.
- return new Integer(hashCode());
- }
- else if (method.getName().equals("close")) {
- // Handle close method: suppress, not valid.
- return null;
- }
- // Invoke method on target Session.
- try {
- Object retVal = method.invoke(this.target, args);
- // If return value is a Query or Criteria, apply transaction timeout.
- // Applies to createQuery, getNamedQuery, createCriteria.
- if (retVal instanceof Query) {
- prepareQuery(((Query) retVal));
- }
- if (retVal instanceof Criteria) {
- prepareCriteria(((Criteria) retVal));
- }
- return retVal;
- }
- catch (InvocationTargetException ex) {
- throw ex.getTargetException();
- }
- }
- }
- }
相关推荐
### hibernateTemplate的常用方法详解 #### 概述 `HibernateTemplate`是Spring框架中用于操作Hibernate的一个便捷工具类,它极大地简化了Hibernate在实际应用中的集成与开发工作。通过`HibernateTemplate`,开发者...
### HibernateTemplate概述与核心功能详解 #### 一、引言 在Java开发领域,特别是企业级应用开发中,数据持久层的设计与实现至关重要。Hibernate作为一款优秀的对象关系映射(ORM)框架,极大地简化了Java应用程序...
### HibernateTemplate的用法总结 #### 一、概述 HibernateTemplate是Spring框架提供的一种操作Hibernate的方式,它简化了Hibernate的使用过程,使开发者无需关注Session的管理与事务控制,极大地提高了开发效率。...
HibernateTemplate 汇总 HibernateTemplate 是 Spring 框架中的一個关键组件,用于简化 Hibernate 的使用,提供了許多实用的方法来进行数据库操作。在本文中,我们将对 HibernateTemplate 的主要方法进行总结和解释...
### HibernateTemplate 的详细介绍与使用范围 #### 一、概述 在Spring框架中,`HibernateTemplate`作为ORM(Object Relational Mapping)技术中的一个重要组件,它提供了简化Hibernate操作的方法集,使得开发人员...
### HibernateTemplate 的方法使用 #### 一、简介与配置方式 **HibernateTemplate** 是 Spring 框架中用于简化 Hibernate 使用的一个工具类。它通过 AOP(面向切面编程)的思想,封装了大量的 CRUD(创建、读取、...
《轻量级 J2EE 企业应用实战: Struts+Spring+Hibernate 整合开发》一书中详述了Spring与Hibernate的整合,其中一个重要组件就是HibernateTemplate。它为简化Hibernate在Spring框架中的使用提供了便利,减少了手动...
本文将深入探讨如何利用Hibernate中的`HibernateTemplate`类进行批量数据删除操作,这不仅能够提高数据处理效率,还能优化数据库性能。 ### HibernateTemplate与批量删除 在Hibernate框架中,`HibernateTemplate`...
本示例将深入探讨如何使用Spring将SessionFactory注入到HibernateTemplate中,从而实现数据库操作的便捷管理。 首先,让我们了解几个关键组件: 1. SessionFactory:这是Hibernate的核心工厂类,用于创建Session...
### 关于使用HibernateTemplate #### 一、简介与背景 在Java企业级应用开发中,持久层技术扮演着至关重要的角色。其中,Hibernate作为一款优秀的ORM(Object Relational Mapping)框架,极大地简化了数据访问层的...
### HibernateTemplate源代码解析 #### 一、简介 `HibernateTemplate`是Spring框架中的一个类,位于`org.springframework.orm.hibernate3`包下。它提供了一系列简化Hibernate数据访问操作的方法,并且能够自动将...
`HibernateTemplate`是Spring框架对Hibernate ORM(对象关系映射)的一种封装,它简化了与数据库交互的复杂性,而"基于HibernateTemplate的代码自动生成"正是为了进一步提升开发效率而设计的一种技术手段。...
HibernateTemplate的简单示例
GenericHibernateDao 继承 HibernateDao,简单封装 HibernateTemplate 各项功能,简化基于Hibernate Dao 的编写。
hibernateTemplate常用方法.htm
### HibernateTemplate 分组统计知识点详解 #### 一、概述 在Java Web开发中,尤其是在使用Spring框架时,经常需要对数据库中的数据进行处理与分析。其中一项常见的需求就是对特定字段进行分组统计,比如按日期...
### HibernateTemplate类的使用详解 #### 一、引言 在Java开发中,持久层框架Hibernate因其优秀的ORM(Object-Relational Mapping)特性被广泛应用。为了更便捷地使用Hibernate,Spring框架提供了一系列工具类来简化...
在使用HibernateTemplate的saveOrUpdate方法时,如果遇到类似`\xE7\x84`这样的十六进制字符串,通常这是由于字符编码不匹配导致的汉字乱码问题。这个问题主要涉及到数据库的字符集设置、应用程序的编码配置以及数据...
`HibernateTemplate`在事务管理、异常转换等方面提供了很多便利,而`HibernateDaoSupport`是一个抽象类,它的目的是为DAO提供对`HibernateTemplate`的便捷访问。 当我们在DAO中继承`HibernateDaoSupport`时,可以...