Java Code Examples for org.springframework.orm.hibernate3.SessionFactoryUtils#getSession()

The following examples show how to use org.springframework.orm.hibernate3.SessionFactoryUtils#getSession() . 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: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according to the settings of this
 * {@code HibernateAccessor} and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession
 */
@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 ((isSingleSession() && TransactionSynchronizationManager.hasResource(getSessionFactory())) ||
		SessionFactoryUtils.isDeferredCloseActive(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 {
		if (isSingleSession()) {
			// single session mode
			logger.debug("Opening single Hibernate Session in OpenSessionInViewInterceptor");
			Session session = SessionFactoryUtils.getSession(
					getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
			applyFlushMode(session, false);
			SessionHolder sessionHolder = new SessionHolder(session);
			TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

			AsyncRequestInterceptor asyncRequestInterceptor =
					new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
		}
		else {
			// deferred close mode
			SessionFactoryUtils.initDeferredClose(getSessionFactory());
		}
	}
}
 
Example 2
Source File: OpenSessionInViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenSessionInViewInterceptorAndDeferredClose() throws Exception {
	SessionFactory sf = mock(SessionFactory.class);
	Session session = mock(Session.class);

	OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
	interceptor.setSessionFactory(sf);
	interceptor.setSingleSession(false);

	given(sf.openSession()).willReturn(session);
	given(session.getSessionFactory()).willReturn(sf);

	interceptor.preHandle(this.webRequest);
	org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
	SessionFactoryUtils.releaseSession(sess, sf);

	// check that further invocations simply participate
	interceptor.preHandle(this.webRequest);

	interceptor.preHandle(this.webRequest);
	interceptor.postHandle(this.webRequest, null);
	interceptor.afterCompletion(this.webRequest, null);

	interceptor.postHandle(this.webRequest, null);
	interceptor.afterCompletion(this.webRequest, null);

	interceptor.preHandle(this.webRequest);
	interceptor.postHandle(this.webRequest, null);
	interceptor.afterCompletion(this.webRequest, null);

	interceptor.postHandle(this.webRequest, null);
	interceptor.afterCompletion(this.webRequest, null);

	verify(session).setFlushMode(FlushMode.MANUAL);
	verify(session).close();
}
 
Example 3
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testClobStringTypeWithSynchronizedSession() throws Exception {
	SessionFactory sf = mock(SessionFactory.class);
	Session session = mock(Session.class);
	given(sf.openSession()).willReturn(session);
	given(session.getSessionFactory()).willReturn(sf);
	given(lobHandler.getClobAsString(rs, "column")).willReturn("content");

	ClobStringType type = new ClobStringType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.CLOB, type.sqlTypes()[0]);
	assertEquals(String.class, type.returnedClass());
	assertTrue(type.equals("content", "content"));
	assertEquals("content", type.deepCopy("content"));
	assertFalse(type.isMutable());

	assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		SessionFactoryUtils.getSession(sf, true);
		type.nullSafeSet(ps, "content", 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(2, synchs.size());
		assertTrue(synchs.get(0).getClass().getName().endsWith("SpringLobCreatorSynchronization"));
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
		((TransactionSynchronization) synchs.get(1)).beforeCompletion();
		((TransactionSynchronization) synchs.get(1)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}

	verify(session).close();
	verify(lobCreator).setClobAsString(ps, 1, "content");
}
 
Example 4
Source File: HibernateDao.java    From java-course-ee with MIT License 4 votes vote down vote up
public Session getSession() {
    return SessionFactoryUtils.getSession(this.sessionFactory, true);
}
 
Example 5
Source File: HibernateDaoSupport.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Obtain a Hibernate Session, either from the current transaction or
 * a new one. The latter is only allowed if "allowCreate" is true.
 * <p><b>Note that this is not meant to be invoked from HibernateTemplate code
 * but rather just in plain Hibernate code.</b> Either rely on a thread-bound
 * Session or use it in combination with {@link #releaseSession}.
 * <p>In general, it is recommended to use
 * {@link #getHibernateTemplate() HibernateTemplate}, either with
 * the provided convenience operations or with a custom
 * {@link org.springframework.orm.hibernate3.HibernateCallback} that
 * provides you with a Session to work on. HibernateTemplate will care
 * for all resource management and for proper exception conversion.
 * @param allowCreate if a non-transactional Session should be created when no
 * transactional Session can be found for the current thread
 * @return the Hibernate Session
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and allowCreate=false
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
 * @deprecated as of Spring 3.2.7, in favor of {@link HibernateTemplate} usage
 */
@Deprecated
protected final Session getSession(boolean allowCreate)
		throws DataAccessResourceFailureException, IllegalStateException {

	return (!allowCreate ?
		SessionFactoryUtils.getSession(getSessionFactory(), false) :
			SessionFactoryUtils.getSession(
					getSessionFactory(),
					this.hibernateTemplate.getEntityInterceptor(),
					this.hibernateTemplate.getJdbcExceptionTranslator()));
}
 
Example 6
Source File: OpenSessionInViewFilter.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Get a Session for the SessionFactory that this filter uses.
 * Note that this just applies in single session mode!
 * <p>The default implementation delegates to the
 * {@code SessionFactoryUtils.getSession} method and
 * sets the {@code Session}'s flush mode to "MANUAL".
 * <p>Can be overridden in subclasses for creating a Session with a
 * custom entity interceptor or JDBC exception translator.
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = SessionFactoryUtils.getSession(sessionFactory, true);
	FlushMode flushMode = getFlushMode();
	if (flushMode != null) {
		session.setFlushMode(flushMode);
	}
	return session;
}