从HibernateTransactionManager迁移到JpaTransactionManager

时间:2011-12-14 11:35:49

标签: hibernate spring jpa sessionfactory transactionmanager

我更改了现有应用程序 中的sessionFactory bean创建,因为各种原因 来自:

<bean id="sessionFactory"
       class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
       <property name="dataSource" ref="dataSource" />
       <property name="mappingLocations" ref="hibernateMappingFiles" />
       <property name="hibernateProperties" ref="hibernateProperties" />
   </bean>

   <tx:annotation-driven transaction-manager="transactionManager" />

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

为:

<bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="spring-jpa" />
    </bean>

    <bean id="sessionFactory" factory-bean="entityManagerFactory" factory-method="getSessionFactory" />

    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

这是我新添加的持久性单元:

<persistence-unit name="spring-jpa">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="none" />
            <property name="javax.persistence.validation.mode" value="none" />
            <property name="hibernate.jdbc.use_streams_for_binary"
                value="true" />
            <property name="hibernate.jdbc.fetch_size" value="100" />
            <property name="hibernate.current_session_context_class" value="org.springframework.orm.hibernate3.SpringSessionContext" />
            <property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml" />
        </properties>
    </persistence-unit>

之后,我在许多 Junit集成测试 的事务块中收到了InvalidComponentException。例如:

createFolder ( "/examples/inheritance" );
transactionTemplate.execute ( new TransactionCallbackWithoutResult () {

            @Override
            protected void doInTransactionWithoutResult ( TransactionStatus status ) {
                for ( Resource r : Arrays.asList ( abstractComponent, concreteAComponent, concreteBComponent ) ) {
                    ComponentVersion c;
                    try {
                        c = componentService.validateAssignValues ( new ModelSource ( loadResource ( r ) ), null, TechnicalVersion.INITIAL_VERSION,
                                ModelVersion.INITIAL_VERSION, ModelVersionIncrement.MAJOR );
                    } catch ( InvalidComponentException e ) {
                        fail ( "Invalid Component: " + e.getMessage () );
                        return;
                    } catch ( IOException e ) {
                        fail ( "IOException: " + e.getMessage () );
                        return;
                    }
                    sessionFactory.getCurrentSession ().save ( c.getModelElement () );
                    sessionFactory.getCurrentSession ().save ( c );
                }
            }
        } );

抛出异常:

catch(InvalidComponentException e){                             失败(“无效组件:”+ e.getMessage());

java.lang.AssertionError: Invalid Component: The inherited component does not exist: name=/examples/inheritance/AbstractComponent
    at org.junit.Assert.fail(Assert.java:93)
    at info.server.component.FindComponentHierarchyTest$1.doInTransactionWithoutResult(FindComponentHierarchyTest.java:83)
    at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:33)
    ...

问题出在sessionFactory.getCurrentSession().save(c);相反,我不得不打电话:

Session session = sessionFactory.getCurrentSession ();
        session.save ( c );
        session.flush ();

现在我知道HibernateTransactionManager与JpaTransactionManager的工作方式不同。但是如果我每次都必须手动调用session.flush(),那就是痛苦和性能杀手。 值得注意的是,当我尝试删除objekt时,我遇到了同样的问题。我必须合并然后删除或分成2个交易。

如何在不添加session.flush()的情况下配置JpaTransactionManager以解决此问题? 我尝试了新添加的persistence.xml,但没有用。 我会很感激,任何帮助都会很棒。


我刚刚检查了我的实际flushmode是什么,两种变体,它都是AUTO。 而且我试图调用em.setFlushMode(FlushModeType.COMMIT)但是flushmode根本没有改变它总是AUTO和((Session)em.getDelegate()).setFlushMode(FlushMode.MANUAL)我得到了这个例外:

org.hibernate.SessionException: Session is closed!
    at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
    at org.hibernate.impl.SessionImpl.setFlushMode(SessionImpl.java:1423)
    at info.novatec.np.server.component.FindComponentHierarchyTest.importComponents(FindComponentHierarchyTest.java:78)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    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.RunBefores.evaluate(RunBefores.java:27)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    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)

1 个答案:

答案 0 :(得分:1)

请注意,您只给我们一个不完整的堆栈跟踪,因为您只打印了异常消息和断言错误,但是没有向我们展示真正的异常堆栈(请执行e.printStackTrace()或catch中的某些内容)。 无论如何,这看起来像是一个商业,非技术/ hibernate / jpa例外,所以我认为它不会带来任何解决方案。

如果它与flush()一起使用,这可能意味着你现在处于flushmode = MANUAL, 而你可能在flushmode = AUTO。

这里描述了Hibernate的可用选项: org.hibernate.FlushMode 顺便说一下,手动flushmode似乎不是JPA规范的一部分: javax.persistence.FlushModeType

所以你可以尝试检查一下你实际的flushmode是什么。 例如:

em.getFlushMode()

您还应该检查结果:

((Session)em.getDelegage()).getFlushMode()

因为您正在导入Hibernate配置文件hibernate.cfg.xml。 也许在hibernate中存在一些错误,这些错误没有在像你这样的特定情况下设置适当的flushmode或其他东西。

检查你的所有应用程序的flushmode是否一致(当你没有明确修改它时......),因为如果你使用带有“readonly = true”的Spring @Transactionnal属性或类似的东西, hibernate flushmode自动设置为手动。 如果你不使用这些注释,那么从2003年开始处理交易回调系统中的交易可能是一个好主意。


实际上似乎有一个JpaTemplate。

查看此代码: http://massapi.com/source/apache-camel-2.5.0/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaTemplateTransactionStrategy.java.html

根据Javadoc,TransactionTemplate用于处理JDBC等低级资源。您应该使用符合您需求的模板,否则您可能会产生奇怪的副作用。