org.springframework.orm.hibernate5.SessionHolder Java Examples

The following examples show how to use org.springframework.orm.hibernate5.SessionHolder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenSessionInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession();
		try {
			TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example #2
Source File: GrailsOpenSessionInViewInterceptor.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
@Override
public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
    SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.getResource(getSessionFactory());
    Session session = sessionHolder != null ? sessionHolder.getSession() : null;
    try {
        super.postHandle(request, model);
        FlushMode flushMode = session != null ? session.getHibernateFlushMode() : null;
        boolean isNotManual = flushMode != FlushMode.MANUAL && flushMode != FlushMode.COMMIT;
        if (session != null && isNotManual) {
            if(logger.isDebugEnabled()) {
                logger.debug("Eagerly flushing Hibernate session");
            }
            session.flush();
        }
    }
    finally {
        if (session != null) {
            session.setHibernateFlushMode(FlushMode.MANUAL);
        }
    }
}
 
Example #3
Source File: HibernatePersistenceContextInterceptor.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
public void destroy() {
    DeferredBindingActions.clear();
    if(!disconnected.isEmpty()) {
        disconnected.pop();
    }
    if (getSessionFactory() == null || decNestingCount() > 0 || getParticipate()) {
        return;
    }

    // single session mode
    SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
    LOG.debug("Closing single Hibernate session in GrailsDispatcherServlet");
    try {
        disconnected.clear();
        SessionFactoryUtils.closeSession(holder.getSession());
    }
    catch (RuntimeException ex) {
        LOG.error("Unexpected exception on closing Hibernate Session", ex);
    }
}
 
Example #4
Source File: HibernatePersistenceContextInterceptor.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
public void init() {
    if (incNestingCount() > 1) {
        return;
    }
    SessionFactory sf = getSessionFactory();
    if (sf == null) {
        return;
    }
    if (TransactionSynchronizationManager.hasResource(sf)) {
        // Do not modify the Session: just set the participate flag.
        setParticipate(true);
    }
    else {
        setParticipate(false);
        LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor");
        Session session = getSession();
        HibernateRuntimeUtils.enableDynamicFilterEnablerIfPresent(sf, session);
        TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    }
}
 
Example #5
Source File: HibernatePersistenceContextInterceptor.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
private Session getSession(boolean allowCreate) {

        Object value = TransactionSynchronizationManager.getResource(getSessionFactory());
        if (value instanceof Session) {
            return (Session) value;
        }

        if (value instanceof SessionHolder) {
            SessionHolder sessionHolder = (SessionHolder) value;
            return sessionHolder.getSession();
        }

        if (allowCreate && hibernateDatastore != null) {
            return hibernateDatastore.openSession();
        }

        throw new IllegalStateException("No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here");
    }
 
Example #6
Source File: OpenSessionInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession();
		try {
			TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example #7
Source File: HibernateCriteriaBuilder.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
@Override
protected void createCriteriaInstance() {
    {
        if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
            participate = true;
            hibernateSession = ((SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory)).getSession();
        }
        else {
            hibernateSession = sessionFactory.openSession();
        }

        criteria = hibernateSession.createCriteria(targetClass);
        cacheCriteriaMapping();
        criteriaMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(criteria.getClass());
    }
}
 
Example #8
Source File: OpenSessionInterceptor.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	Assert.state(sf != null, "No SessionFactory set");

	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession(sf);
		try {
			TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example #9
Source File: OpenSessionInterceptor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	Assert.state(sf != null, "No SessionFactory set");

	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession(sf);
		try {
			TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example #10
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or a
 * transaction timeout.
 *
 * @param criteria the Criteria object to prepare
 * @deprecated Deprecated because Hibernate Criteria are deprecated
 */
@Deprecated
protected void prepareCriteria(Criteria criteria) {
    if (cacheQueries) {
        criteria.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        criteria.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}
 
Example #11
Source File: IntegrationTestBase.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void unbindSession()
{
    SessionFactory sessionFactory = (SessionFactory) webApplicationContext.getBean( "sessionFactory" );

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
        .unbindResource( sessionFactory );

    SessionFactoryUtils.closeSession( sessionHolder.getSession() );
}
 
Example #12
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Prepare the given Query object, applying cache settings and/or a
 * transaction timeout.
 *
 * @param query the Query object to prepare
 */
protected void prepareQuery(org.hibernate.query.Query query) {
    if (cacheQueries) {
        query.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        query.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}
 
Example #13
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
@Override
public <T1> T1 executeWithExistingOrCreateNewSession(SessionFactory sessionFactory, Closure<T1> callable) {
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if(sessionHolder == null) {
        return executeWithNewSession(callable);
    }
    else {
        return callable.call(sessionHolder.getSession());
    }
}
 
Example #14
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Prepare the given Query object, applying cache settings and/or a
 * transaction timeout.
 *
 * @param jpaQuery the Query object to prepare
 */
protected <T> void prepareCriteria(Query<T> jpaQuery) {
    if (cacheQueries) {
        jpaQuery.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        jpaQuery.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        jpaQuery.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}
 
Example #15
Source File: DhisTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Binds a Hibernate Session to the current thread.
 */
private void bindSession()
{
    SessionFactory sessionFactory = (SessionFactory) getBean( "sessionFactory" );
    Session session = sessionFactory.openSession();

    TransactionSynchronizationManager.bindResource( sessionFactory, new SessionHolder( session ) );
}
 
Example #16
Source File: DhisTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Unbinds and closes the bound Hibernate Session from the current thread.
 */
private void unbindSession()
{
    SessionFactory sessionFactory = (SessionFactory) getBean( "sessionFactory" );

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource( sessionFactory );

    SessionFactoryUtils.closeSession( sessionHolder.getSession() );
}
 
Example #17
Source File: IntegrationTestBase.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void bindSession()
{
    SessionFactory sessionFactory = (SessionFactory) webApplicationContext.getBean( "sessionFactory" );
    Session session = sessionFactory.openSession();
    session.setHibernateFlushMode(FlushMode.ALWAYS);
    TransactionSynchronizationManager.bindResource( sessionFactory, new SessionHolder( session ) );
}
 
Example #18
Source File: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Unbind the Hibernate {@code Session} from the thread and close it).
 * @see TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
		logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
		SessionFactoryUtils.closeSession(sessionHolder.getSession());

	}
}
 
Example #19
Source File: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
	}
}
 
Example #20
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unbind the Hibernate {@code Session} from the thread and close it).
 * @see TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
		logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
		SessionFactoryUtils.closeSession(sessionHolder.getSession());
	}
}
 
Example #21
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
	}
}
 
Example #22
Source File: OpenSessionInViewInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Unbind the Hibernate {@code Session} from the thread and close it).
 * @see TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, @Nullable Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
		logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
		SessionFactoryUtils.closeSession(sessionHolder.getSession());
	}
}
 
Example #23
Source File: OpenSessionInViewInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) {
		return;
	}

	if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor);
	}
}
 
Example #24
Source File: OpenSessionInViewInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Unbind the Hibernate {@code Session} from the thread and close it).
 * @see TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, @Nullable Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
		logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
		SessionFactoryUtils.closeSession(sessionHolder.getSession());
	}
}
 
Example #25
Source File: OpenSessionInViewInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) {
		return;
	}

	if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor);
	}
}
 
Example #26
Source File: AsyncRequestInterceptor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) {
	this.sessionFactory = sessionFactory;
	this.sessionHolder = sessionHolder;
}
 
Example #27
Source File: AsyncRequestInterceptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) {
	this.sessionFactory = sessionFactory;
	this.sessionHolder = sessionHolder;
}
 
Example #28
Source File: GrailsSessionContext.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
protected TransactionSynchronization createSpringSessionSynchronization(SessionHolder sessionHolder) {
    return new SpringSessionSynchronization(sessionHolder, sessionFactory);
}
 
Example #29
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
protected boolean isSessionTransactional(Session session) {
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    return sessionHolder != null && sessionHolder.getSession() == session;
}
 
Example #30
Source File: AsyncRequestInterceptor.java    From java-technology-stack with MIT License 4 votes vote down vote up
public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) {
	this.sessionFactory = sessionFactory;
	this.sessionHolder = sessionHolder;
}