Spring 3.1和Hibernate 4:“HibernateException:当前线程找不到会话”从单元测试中调用DAO方法时

时间:2012-10-09 21:02:05

标签: java spring hibernate unit-testing exception

我正在使用Spring 3.1和Hibernate 4.1,当我运行存储库测试时,我目前遇到以下异常:

Caused by: org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1041)

这是DAO的样子。它使用与其他人基本上使用的相同的泛型dao模式:

@Repository
public class UserRepository extends RepositorySupport<User> {

    public UserRepository() {
        super(User.class);
    }

    public User findByUsername(final String username) {
        Query query = getCurrentSession().createQuery(
            "from User user " +
            "where user.username = :username"
        );

        return (User) query.setParameter("username", username)
            .uniqueResult();
    }

我通常不会做的唯一不同的是我不再使用getHibernateTemplate() - 这就是我怀疑事情不起作用的原因。我宁愿不使用这种方法,如果我可以避免它,因为结果代码看起来很糟糕。

我的hibernate bean看起来像这样:

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>hibernate/tag.hbm.xml</value>
            <value>hibernate/address.hbm.xml</value>
            <value>hibernate/user.hbm.xml</value>
        </list>
    </property>
    <property name="namingStrategy">
        <bean class="org.hibernate.cfg.ImprovedNamingStrategy"/>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="javax.persistence.validation.mode">none</prop>

            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}
            </prop>
            <prop key="hibernate.generate_statistics">false</prop>

            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.format_sql">true</prop>

            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="hibernate.cache.provider_class">

            </prop>
        </props>
    </property>
</bean>

<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>

<bean id="transactionManager"
      class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

<!--
<bean id="hibernateInterceptor"
      class="org.springframework.orm.hibernate4.HibernateInterceptor">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
-->

<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find*" read-only="true" propagation="REQUIRED"/>
        <tx:method name="get*" read-only="true" propagation="REQUIRED"/>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:advisor advice-ref="transactionAdvice"
                 pointcut="execution(* *..service.*.*(..))" order="1"/>
    <!-- gets sub packages like service.user -->
    <aop:advisor advice-ref="transactionAdvice"
                 pointcut="execution(* *..service.*.*.*(..))" order="2"/>
</aop:config>

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="com.realtywebsite.repositories,com.realtywebsite.service"/>

<task:annotation-driven />

我的测试代码看起来像这样(我必须弄平它,因为我的测试从一个普通的父测试类扩展):

@ContextConfiguration(locations = {
    ObjectMother.APPLICATION_CONTEXT,
    ObjectMother.WEB_CONTEXT
})
public abstract class DatabaseTest extends AbstractTransactionalJUnit4SpringContextTests {


    @Test
    public void delete() {
        userRepository.delete(1);
        flush();

        assertFalse(userRepository.exists(1));
    }

    ...

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

不推荐使用类AbstractTransactionalJUnit4SpringContextTests

您有两种选择:

  • AbstractTransactionalJUnit4SpringContextTests
  • 延伸
  • 使用SpringJUnit4ClassRunner(然后您需要附加@Transactional

我希望能解决这个问题。

答案 1 :(得分:0)

我遇到了从hibernate 3迁移到hibernate 4的问题。简而言之,没有提供程序可以打开并将hibernate会话绑定到当前线程。因此sessionFactory将没有currentSession(因为它存储在ThreadLocal变量中)。解决Web应用程序最流行的方法是使用OpenSessionInViewInterceptorOpenSessionInViewFilter。在你的情况下,我建议你自己写。 Here is an example.