Java Code Examples for org.springframework.orm.hibernate5.SessionHolder

The following examples show how to use org.springframework.orm.hibernate5.SessionHolder. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: OpenSessionInterceptor.java    License: 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 2
Source Project: java-technology-stack   Source File: OpenSessionInterceptor.java    License: 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 3
Source Project: lams   Source File: OpenSessionInterceptor.java    License: 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 4
@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 5
@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 6
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 7
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 8
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 9
Source Project: gorm-hibernate5   Source File: HibernateCriteriaBuilder.java    License: 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 10
/**
 * 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 11
/**
 * 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 12
/**
 * 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 13
/**
 * 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 14
/**
 * 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 15
/**
 * 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 16
/**
 * 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 17
/**
 * 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 18
Source Project: gorm-hibernate5   Source File: GrailsHibernateTemplate.java    License: 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 19
Source Project: gorm-hibernate5   Source File: GrailsHibernateTemplate.java    License: 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 20
Source Project: gorm-hibernate5   Source File: GrailsHibernateTemplate.java    License: 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 21
Source Project: gorm-hibernate5   Source File: GrailsHibernateTemplate.java    License: 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 22
Source Project: dhis2-core   Source File: DhisTest.java    License: 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 23
Source Project: dhis2-core   Source File: DhisTest.java    License: 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 24
private void bindSession()
{
    SessionFactory sessionFactory = (SessionFactory) webApplicationContext.getBean( "sessionFactory" );
    Session session = sessionFactory.openSession();
    session.setHibernateFlushMode(FlushMode.ALWAYS);
    TransactionSynchronizationManager.bindResource( sessionFactory, new SessionHolder( session ) );
}
 
Example 25
private void unbindSession()
{
    SessionFactory sessionFactory = (SessionFactory) webApplicationContext.getBean( "sessionFactory" );

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

    SessionFactoryUtils.closeSession( sessionHolder.getSession() );
}
 
Example 26
Source Project: spring-analysis-note   Source File: AsyncRequestInterceptor.java    License: MIT License 4 votes vote down vote up
public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) {
	this.sessionFactory = sessionFactory;
	this.sessionHolder = sessionHolder;
}
 
Example 27
Source Project: java-technology-stack   Source File: AsyncRequestInterceptor.java    License: MIT License 4 votes vote down vote up
public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) {
	this.sessionFactory = sessionFactory;
	this.sessionHolder = sessionHolder;
}
 
Example 28
Source Project: lams   Source File: AsyncRequestInterceptor.java    License: 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 29
public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) {
	this.sessionFactory = sessionFactory;
	this.sessionHolder = sessionHolder;
}
 
Example 30
Source Project: gorm-hibernate5   Source File: GrailsSessionContext.java    License: Apache License 2.0 4 votes vote down vote up
protected TransactionSynchronization createSpringSessionSynchronization(SessionHolder sessionHolder) {
    return new SpringSessionSynchronization(sessionHolder, sessionFactory);
}