带有Hibernate 4的Spring 3 - 单元测试失败,找不到当前线程的Session

时间:2013-03-18 23:11:46

标签: java spring hibernate junit

我已经使用了Spring和Hibernate多年,但这是我使用Spring 3和Hibernate 4的第一个项目。

我设置了Model类:

@Entity
@Table(name = "DICTIONARY_ENTRY", uniqueConstraints = @UniqueConstraint(columnNames = {
        "DICTIONARY_UUID", "ANAGRAM", "WORD" }))
public class DictionaryEntry extends Pojo implements
        Comparable<DictionaryEntry> {
    @Column(name = "ANAGRAM", nullable = false)
    private String anagram;

    @Column(name = "WORD", nullable = false, unique = true)
    private String word;

    @Column(name = "DEFINITION", nullable = false)
    private String definition;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "DICTIONARY_UUID", referencedColumnName = "UUID", nullable=false)
    private Dictionary dictionary;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "fromEntry")
    /*package*/ Set<CrossReference> fromReferences;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "toEntry")
    /*package*/ Set<CrossReference> toReferences;

根据Spring手册中的说明,我然后设置我的DAO并注入org.springframework.orm.hibernate4.LocalSessionFactoryBean的实例。然后我调用getSession(),它是:

  /**
   * Get the current session for a hibernate query
   * @return the current session
   */
  protected Session getSession(){
    return sessionFactory.getCurrentSession();
  }

然后我运行我的单元测试,在我的会话工厂中注入并运行此方法:

object = (T) getSession().save(object);

引发:

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:980)
    at com.heavyweight.lexaholic.dao.hibernate.HibernateDAO.getSession(HibernateDAO.java:86)
    at com.heavyweight.lexaholic.dao.hibernate.HibernateDAO.create(HibernateDAO.java:59)
    at com.heavyweight.lexaholic.dao.hibernate.lexicon.DictionaryEntryHibernateDAOTest.testCRD(DictionaryEntryHibernateDAOTest.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

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:980)
    at com.heavyweight.lexaholic.dao.hibernate.HibernateDAO.getSession(HibernateDAO.java:86)
    at com.heavyweight.lexaholic.dao.hibernate.HibernateDAO.commit(HibernateDAO.java:41)
    at com.heavyweight.lexaholic.dao.hibernate.lexicon.DictionaryEntryHibernateDAOTest.tearDown(DictionaryEntryHibernateDAOTest.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:37)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

这是Spring配置:

  <bean id="testDatabase" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"><value>org.h2.Driver</value></property>
    <property name="url"><value>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</value></property>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
  </bean>

  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="testDatabase"/>
  </bean>

  <bean id="testSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="testDatabase" />
    <property name="annotatedClasses">
      <list>
        <value>com.heavyweight.lexaholic.model.lexicon.CrossReference</value>
        <value>com.heavyweight.lexaholic.model.lexicon.Dictionary</value>
        <value>com.heavyweight.lexaholic.model.lexicon.DictionaryEntry</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.H2Dialect
        hibernate.show_sql=false
        hibernate.jdbc.batch_size=0
        hibernate.hbm2ddl.auto=create-drop
        hibernate.use_sql_comments=false
    </value>
    </property>
  </bean>

  <bean id="dictionaryEntryDAO" class="com.heavyweight.lexaholic.dao.hibernate.lexicon.DictionaryEntryHibernateDAO" init-method="init">
    <property name="sessionFactory" ref="testSessionFactory" />
  </bean>

3 个答案:

答案 0 :(得分:4)

您需要修改两件事:

首先,您使用Hibernate进行持久化,因此您需要使用HibernateTransactionManager而不是DataSourceTransactionManager。

<!-- Transaction Configuration For All Services (including Hibernate and MyBatis)-->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- Transaction: enable annotation-driven transaction -->
<!--Put @Transactional on service impl instead of service interface-->
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>

其次,您正在使用Hibernate 4.x,因此您需要像这样配置 当前会话上下文类

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>

有关信息,请参阅http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/

我希望你通过它

答案 1 :(得分:2)

我在使用hibernate 3.6的spring 3应用程序中的junit测试中遇到了同样的问题 当应用程序在应用程序服务器上运行时,将使用会话筛选器管理会话:

<filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>

但是当运行junit时它没有加载,你必须在你的测试中模拟它 建议的一个解决方案是使用@TransactionConfiguration或扩展AbstractTransactionalJUnit4SpringContextTests但如果你有一个使用@Service @Transactional注释的服务层类并且你在测试中多次调用它,它就不起作用。

根据this帖子,我解决了以下问题:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:context.xml"})
public class JUnitTestBase extends AbstractJUnit4SpringContextTests {
    @Autowired
    protected Log logger;

    @Autowired
    protected SessionFactory sessionFactory;

    protected FlushMode flushMode = FlushMode.MANUAL;

    @Before
    public void setUp() throws Exception {
        Session session = getSession(this.sessionFactory);
        TransactionSynchronizationManager.bindResource(sessionFactory,new SessionHolder(session));
        logger.debug("Hibernate session is bound");
    }

    @After
    public void tearDown() throws Exception {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
        closeSession(sessionHolder.getSession(), sessionFactory);
        logger.debug("Hibernate session is closed");
    }

    protected void closeSession(Session session, SessionFactory sessionFactory) {
        SessionFactoryUtils.closeSession(session);
    }

    protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
        FlushMode flushMode = this.flushMode;
        if (flushMode != null) {
            session.setFlushMode(flushMode);
        }
        return session;
    }
}

答案 2 :(得分:1)

我认为您的测试可能缺少TransactionConfiguration注释。请尝试以下方法 -

@TransactionConfiguration(transactionManager="txManager")

或者,您可以按如下方式更改事务管理器的bean定义 -

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="testDatabase"/>

默认情况下,spring尝试查找'transactionManager'bean。