3

I have used Spring and Hibernate for years, but this is my first project using Spring 3 and Hibernate 4.

I set up the Model class such:

@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;

Per the directions in the Spring manual, I then set up my DAO and inject in an instance of org.springframework.orm.hibernate4.LocalSessionFactoryBean. Then I call getSession() which is:

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

I then run my unit test, inject in my session factory and run this method:

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

Which throws:

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)

Here's the Spring configuration:

  <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>
4

3 回答 3

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/

希望你通过

于 2013-03-19T01:09:24.290 回答
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 注释的服务层类并且您在测试中多次调用它,则它不起作用。

根据这篇文章,我解决了以下问题:

@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;
    }
}
于 2013-11-19T17:58:38.123 回答
1

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

@TransactionConfiguration(transactionManager="txManager")

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

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

默认情况下,spring 会尝试查找“transactionManager”bean。

于 2013-03-19T00:37:04.873 回答