Example usage for org.springframework.orm.hibernate5 HibernateCallback doInHibernate

List of usage examples for org.springframework.orm.hibernate5 HibernateCallback doInHibernate

Introduction

In this page you can find the example usage for org.springframework.orm.hibernate5 HibernateCallback doInHibernate.

Prototype

@Nullable
T doInHibernate(Session session) throws HibernateException;

Source Link

Document

Gets called by HibernateTemplate.execute with an active Hibernate Session .

Usage

From source file:org.springframework.orm.hibernate5.HibernateTemplate.java

/**
 * 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/*  w w  w  . j  av  a  2s  .co  m*/
 * @return a result object returned by the action, or {@code null}
 * @throws DataAccessException in case of Hibernate errors
 */
@SuppressWarnings("deprecation")
@Nullable
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession)
        throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");

    Session session = null;
    boolean isNew = false;
    try {
        session = obtainSessionFactory().getCurrentSession();
    } catch (HibernateException ex) {
        logger.debug("Could not retrieve pre-bound Hibernate session", ex);
    }
    if (session == null) {
        session = obtainSessionFactory().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 (PersistenceException ex) {
        if (ex.getCause() instanceof HibernateException) {
            throw SessionFactoryUtils.convertHibernateAccessException((HibernateException) ex.getCause());
        }
        throw ex;
    } catch (RuntimeException ex) {
        // Callback code threw application exception...
        throw ex;
    } finally {
        if (isNew) {
            SessionFactoryUtils.closeSession(session);
        } else {
            disableFilters(session);
        }
    }
}