当前位置: 首页>>代码示例>>Java>>正文


Java SessionFactoryUtils类代码示例

本文整理汇总了Java中org.springframework.orm.hibernate3.SessionFactoryUtils的典型用法代码示例。如果您正苦于以下问题:Java SessionFactoryUtils类的具体用法?Java SessionFactoryUtils怎么用?Java SessionFactoryUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


SessionFactoryUtils类属于org.springframework.orm.hibernate3包,在下文中一共展示了SessionFactoryUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: invoke

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
@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();
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:21,代码来源:OpenSessionInterceptor.java

示例2: afterCompletion

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
/**
 * 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());
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:OpenSessionInViewInterceptor.java

示例3: testOpenSessionInterceptor

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
@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();
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:26,代码来源:OpenSessionInViewTests.java

示例4: countByExample

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
/**
 * @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();
		}
	});
}
 
开发者ID:liuling07,项目名称:QiQuYingServer,代码行数:28,代码来源:BaseDAO.java

示例5: afterCompletion

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
/**
 * 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
 */
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());
		}
	}
}
 
开发者ID:deathspeeder,项目名称:class-guard,代码行数:22,代码来源:OpenSessionInViewInterceptor.java

示例6: findById

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
/**
 * @see GenericDao#findById(Serializable, boolean)
 */
@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock) throws DataAccessException {
   T entity;

   try {
      if (lock) {
         entity =
            (T) getSession().load(
               getPersistentClass(), id, LockMode.UPGRADE);
      } else {
         entity = (T) getSession().load(getPersistentClass(), id);
      }
   } catch (HibernateException e) {
      throw SessionFactoryUtils.convertHibernateAccessException(e);
   }

   return entity;
}
 
开发者ID:kumaramit01,项目名称:FlowService,代码行数:22,代码来源:GenericDaoImpl.java

示例7: findByExample

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
/**
 * @see GenericDao#findByExample(Object, String...)
 */
@SuppressWarnings("unchecked")
public List<T> findByExample(T exampleInstance, String... excludeProperty)
      throws DataAccessException {
   try {
      Criteria crit = getSession().createCriteria(getPersistentClass());
      Example example = Example.create(exampleInstance);
      for (String exclude : excludeProperty) {
         example.excludeProperty(exclude);
      }
      crit.add(example);
      return crit.list();
   } catch (HibernateException e) {
      throw SessionFactoryUtils.convertHibernateAccessException(e);
   }
}
 
开发者ID:kumaramit01,项目名称:FlowService,代码行数:19,代码来源:GenericDaoImpl.java

示例8: lock

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
@Override
public void lock(final Account... accounts) throws LockingException {
    if (ArrayUtils.isEmpty(accounts)) {
        return;
    }
    Long[] ids = EntityHelper.toIds(accounts);
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    try {
        session
                .createQuery("select l.id from AccountLock l where l.id in (:ids)")
                .setLockOptions(new LockOptions(LockMode.PESSIMISTIC_WRITE))
                .setParameterList("ids", ids)
                .list();
    } catch (JDBCException e) {
        handleException(e);
    }
}
 
开发者ID:crypto-coder,项目名称:open-cyclos,代码行数:18,代码来源:DirectLockHandlerFactory.java

示例9: unbindSession

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
private void unbindSession() {
    if (sessionFactory == null) {
        throw new IllegalStateException("No sessionFactory property provided");
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    try {
        if (!FlushMode.MANUAL.equals(sessionHolder.getSession().getFlushMode())) {
            sessionHolder.getSession().flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        TransactionSynchronizationManager.unbindResource(sessionFactory);
        SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
}
 
开发者ID:psramkumar,项目名称:grails-jsf2-plugin,代码行数:17,代码来源:GrailsHibernatePhaseListener.java

示例10: preHandle

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
/**
 * 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());
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:46,代码来源:OpenSessionInViewInterceptor.java

示例11: testOpenSessionInViewInterceptorWithSingleSession

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
@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();
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:41,代码来源:OpenSessionInViewTests.java

示例12: testOpenSessionInViewInterceptorAndDeferredClose

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
@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();
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:37,代码来源:OpenSessionInViewTests.java

示例13: testClobStringTypeWithSynchronizedSession

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
@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");
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:37,代码来源:LobTypeTests.java

示例14: getSession

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
/**
 * ��ȡSession����
 * @return
 */
protected Session getSession(){
	return (!this.template.isAllowCreate() ?
	    SessionFactoryUtils.getSession(this.template.getSessionFactory(), false) :
			SessionFactoryUtils.getSession(
					this.template.getSessionFactory(),
					this.template.getEntityInterceptor(),
					this.template.getJdbcExceptionTranslator()));
}
 
开发者ID:java-scott,项目名称:java-project,代码行数:13,代码来源:DaoSupport.java

示例15: queryForBean

import org.springframework.orm.hibernate3.SessionFactoryUtils; //导入依赖的package包/类
public List<Object> queryForBean(Object bean,SqlConfig hqlConfig) {
		HqlQuery hqlQuery = HibernateClassUtils.getHql(bean, hqlConfig);
		String queryString = hqlQuery.getQueryString();
		Map<String,Object> nameKeyMap = hqlQuery.getNameKeyMap();
	Session session = openSession();
	Query query = session.createQuery(queryString);
	
	if (nameKeyMap != null && nameKeyMap.size() > 0) {
		query.setProperties(nameKeyMap);
	}
	List<Object> resultList = query.list();
	SessionFactoryUtils.closeSession(session);
	return resultList;
}
 
开发者ID:thinking-github,项目名称:nbone,代码行数:15,代码来源:HibernateDao.java


注:本文中的org.springframework.orm.hibernate3.SessionFactoryUtils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。