java.lang.ClassCastException: $Proxy3 cannot be cast to org.hibernate.impl.SessionImpl

    今天写移交记录模块时出现如下错误:
java.lang.ClassCastException: $Proxy3 cannot be cast to org.hibernate.impl.SessionImpl

	at org.hibernate.criterion.DetachedCriteria.getExecutableCriteria(DetachedCriteria.java:51)

	at cn.sh.cares.framework.dao.hibernate.AbstractHibernateEntityManager$1.doInHibernate(AbstractHibernateEntityManager.java:123)

	at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:356)

	at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:329)
出错代码如下:
    public List searchWithPagination(final DetachedCriteria queryCondition, final Pagination pagination, final String[] initFields) {

	return (List) getHibernateTemplate().execute(new HibernateCallback() {

	    public Object doInHibernate(Session session) throws HibernateException, SQLException {

		initDetachedCriteriaFecthMode(queryCondition, initFields);

		Criteria criteria = queryCondition.getExecutableCriteria(session);

		if(pagination != null) {

		    Object count = criteria.setProjection(Projections.rowCount()).uniqueResult();

		    if(count != null) {

			pagination.setTotalCount(((Integer) count).intValue());

		    }

		    criteria.setFirstResult(pagination.getStartIndex());

		    criteria.setMaxResults(pagination.getPageSize());

		}

		criteria.setProjection(null);

		List results = criteria.list();

		if(results == null) return Collections.EMPTY_LIST;

		return results;

	    }

	});

    }
google里也没有找到类似的,后来看了一下spring HibernateTemplate源代码,发现这段:
protected Object doExecute(HibernateCallback action, boolean enforceNewSession, boolean enforceNativeSession)

			throws DataAccessException {

.........
		try {

			previousFlushMode = applyFlushMode(session, existingTransaction);

			enableFilters(session);

			Session sessionToExpose =

					(enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session)); //代理session

			Object result = action.doInHibernate(sessionToExpose);

			flushIfNecessary(session, existingTransaction);

			return result;

		}

}
这是因为使用了代理session,才导致session往SessionImplementor强制转换的时候出错。只要在execute(new HibernateCallback() 后在加上参数true就可以,这其实就是boolean enforceNativeSession的值。

你可能感兴趣的:(spring,object,session,list,null,Integer)