org.springframework.orm.hibernate3.SessionFactoryUtils Java Examples

The following examples show how to use org.springframework.orm.hibernate3.SessionFactoryUtils. 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 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 #2
Source File: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Unbind the Hibernate {@code Session} from the thread and close it (in
 * single session mode), or process deferred close for all sessions that have
 * been opened during the current request (in deferred close mode).
 * @see org.springframework.transaction.support.TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		if (isSingleSession()) {
			// single session mode
			SessionHolder sessionHolder =
					(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
			logger.debug("Closing single Hibernate Session in OpenSessionInViewInterceptor");
			SessionFactoryUtils.closeSession(sessionHolder.getSession());
		}
		else {
			// deferred close mode
			SessionFactoryUtils.processDeferredClose(getSessionFactory());
		}
	}
}
 
Example #3
Source File: OpenSessionInViewTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testOpenSessionInterceptor() throws Exception {
	final SessionFactory sf = mock(SessionFactory.class);
	final Session session = mock(Session.class);

	OpenSessionInterceptor interceptor = new OpenSessionInterceptor();
	interceptor.setSessionFactory(sf);

	Runnable tb = new Runnable() {
		@Override
		public void run() {
			assertTrue(TransactionSynchronizationManager.hasResource(sf));
			assertEquals(session, SessionFactoryUtils.getSession(sf, false));
		}
	};
	ProxyFactory pf = new ProxyFactory(tb);
	pf.addAdvice(interceptor);
	Runnable tbProxy = (Runnable) pf.getProxy();

	given(sf.openSession()).willReturn(session);
	given(session.isOpen()).willReturn(true);
	tbProxy.run();
	verify(session).setFlushMode(FlushMode.MANUAL);
	verify(session).close();
}
 
Example #4
Source File: BaseDAO.java    From QiQuYingServer with Apache License 2.0 6 votes vote down vote up
/**
 * @Title: countByExample
 * @Description: 根据模型统计
 * @param @param entityBean
 * @param @return
 * @return int
 */
public <T> int countByExample(final T obj) {
	return (Integer) getHibernateTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {
		public Integer doInHibernate(Session s) throws HibernateException, SQLException {
			// 组装属性
			Criteria criteria = s.createCriteria(obj.getClass()).setProjection(Projections.projectionList().add(Projections.rowCount()))
					.add(Example.create(obj));
			if (getHibernateTemplate().isCacheQueries()) {
				criteria.setCacheable(true);
				if (getHibernateTemplate().getQueryCacheRegion() != null)
					criteria.setCacheRegion(getHibernateTemplate().getQueryCacheRegion());
			}
			if (getHibernateTemplate().getFetchSize() > 0)
				criteria.setFetchSize(getHibernateTemplate().getFetchSize());
			if (getHibernateTemplate().getMaxResults() > 0)
				criteria.setMaxResults(getHibernateTemplate().getMaxResults());
			SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory());
			return (Integer) criteria.uniqueResult();
		}
	});
}
 
Example #5
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 #6
Source File: OpenSessionInViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenSessionInViewInterceptorWithSingleSession() throws Exception {
	SessionFactory sf = mock(SessionFactory.class);
	Session session = mock(Session.class);

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

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

	interceptor.preHandle(this.webRequest);
	assertTrue(TransactionSynchronizationManager.hasResource(sf));

	// check that further invocations simply participate
	interceptor.preHandle(this.webRequest);
	assertEquals(session, SessionFactoryUtils.getSession(sf, false));

	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);
	assertTrue(TransactionSynchronizationManager.hasResource(sf));

	interceptor.afterCompletion(this.webRequest, null);
	assertFalse(TransactionSynchronizationManager.hasResource(sf));

	verify(session).setFlushMode(FlushMode.MANUAL);
	verify(session).close();
}
 
Example #7
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 #8
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 #9
Source File: AsyncRequestInterceptor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private void closeAfterTimeout() {
	if (this.timeoutInProgress) {
		logger.debug("Closing Hibernate Session after async request timeout");
		SessionFactoryUtils.closeSession(this.sessionHolder.getSession());
	}
}
 
Example #10
Source File: OpenSessionInViewTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testOpenSessionInViewInterceptorWithSingleSessionAndJtaTm() throws Exception {
	final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
	Session session = mock(Session.class);

	TransactionManager tm = mock(TransactionManager.class);
	given(tm.getTransaction()).willReturn(null);
	given(tm.getTransaction()).willReturn(null);

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

	given(sf.openSession()).willReturn(session);
	given(sf.getTransactionManager()).willReturn(tm);
	given(sf.getTransactionManager()).willReturn(tm);
	given(session.isOpen()).willReturn(true);

	interceptor.preHandle(this.webRequest);
	assertTrue(TransactionSynchronizationManager.hasResource(sf));

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

	assertEquals(session, SessionFactoryUtils.getSession(sf, false));

	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);
	assertTrue(TransactionSynchronizationManager.hasResource(sf));

	interceptor.afterCompletion(this.webRequest, null);
	assertFalse(TransactionSynchronizationManager.hasResource(sf));

	verify(session).setFlushMode(FlushMode.MANUAL);
	verify(session).close();
}
 
Example #11
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 #12
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 #13
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;
}
 
Example #14
Source File: HibernateDaoSupport.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Close the given Hibernate Session, created via this DAO's SessionFactory,
 * if it isn't bound to the thread (i.e. isn't a transactional Session).
 * <p>Typically used in plain Hibernate code, in combination with
 * {@link #getSession} and {@link #convertHibernateAccessException}.
 * @param session the Session to close
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#releaseSession
 * @deprecated as of Spring 3.2.7, in favor of {@link HibernateTemplate} usage
 */
@Deprecated
protected final void releaseSession(Session session) {
	SessionFactoryUtils.releaseSession(session, getSessionFactory());
}
 
Example #15
Source File: OpenSessionInViewFilter.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Close the given Session.
 * Note that this just applies in single session mode!
 * <p>Can be overridden in subclasses, e.g. for flushing the Session before
 * closing it. See class-level javadoc for a discussion of flush handling.
 * Note that you should also override getSession accordingly, to set
 * the flush mode to something else than NEVER.
 * @param session the Session used for filtering
 * @param sessionFactory the SessionFactory that this filter uses
 */
protected void closeSession(Session session, SessionFactory sessionFactory) {
	SessionFactoryUtils.closeSession(session);
}