【问题标题】:Switched to JPA, now I always get TransactionRequiredException on any insert切换到 JPA,现在我总是在任何插入时得到 TransactionRequiredException
【发布时间】:2014-09-24 06:13:14
【问题描述】:

我有一个 Spring4 网络应用程序。最初我使用的是 Hibernate SessionFactory,并使用 Spring Hibernate API 进行开发。一切正常。也许我愚蠢地决定最近改用 JPA,而 Hibernate 仍然是我的提供者。我重新配置了我的 Spring 设置并重写了我的大部分代码。最初经过测试,我的所有数据库读取都可以正常工作,他们确实这样做了。然后我尝试了数据库写入,它们都失败了:

javax.persistence.TransactionRequiredException: no transaction is in progress
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:970)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:342)
    at com.sun.proxy.$Proxy47.flush(Unknown Source)
    at com.taubler.oversite.dao.impl.EntityDaoImpl.insert(EntityDaoImpl.java:65)
    ...

请记住,我的代码在使用 HibernateTemplateSessionFactoryHibernateTransactionManager 等时运行良好。我的业务逻辑类以及我的 DAO 都像以前一样使用 @Transactional 进行注释。

看起来 Hibernate 正在尝试创建事务,因为我在堆栈跟踪之前的日志中看到以下内容:

2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - initial autocommit status: true
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - disabling autocommit
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.internal.SessionImpl - Opened session at timestamp: 14115372286
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.internal.SessionImpl - Setting flush mode to: AUTO
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.internal.SessionImpl - Setting cache mode to: NORMAL
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.event.internal.AbstractSaveEventListener - Transient instance of: com.taubler.oversite.entities.EmailAddress
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.event.internal.DefaultPersistEventListener - Saving transient instance
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.event.internal.AbstractSaveEventListener - Saving [com.taubler.oversite.entities.EmailAddress#<null>]
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.engine.spi.IdentifierValue - ID unsaved-value: null
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.event.internal.AbstractSaveEventListener - Delaying identity-insert due to no transaction in progress
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.internal.SessionImpl - Opened session at timestamp: 14115372287
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.internal.SessionImpl - Setting flush mode to: AUTO
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.internal.SessionImpl - Setting cache mode to: NORMAL
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.engine.transaction.spi.AbstractTransactionImpl - rolling back
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - rolled JDBC Connection
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - re-enabling autocommit
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl - after transaction completion
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.internal.SessionImpl - after transaction completion
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.internal.SessionImpl - Closing session
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Closing logical connection
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.engine.jdbc.internal.JdbcResourceRegistryImpl - Closing JDBC container [org.hibernate.engine.jdbc.internal.JdbcResourceRegistryImpl@2c4e3947]
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Releasing JDBC connection
2014-09-24 05:40:28 [http-bio-8080-exec-3] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Released JDBC connection
2014-09-24 05:40:28 [http-bio-8080-exec-3] TRACE org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Logical connection closed

这是一些相关的代码。首先,我的 spring 配置 XML 中的 sn-ps:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.taubler.oversite.entities" />
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.jdbc.batch_size">20</prop>
            <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>               
         </props>
      </property>
</bean>

<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

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

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${db.driver}" />
    <property name="url" value="${db.url}" />
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
</bean>

一个示例业务逻辑(管理器)类。这个类是@Autowired进入SpringMVC Controller,所以Controller在调用代理:

...

@Autowired
private EmailAddressDao emailAddressDao;
...

@Override
@Transactional
public EmailAddress addEmailAddress(User user, String email) {  
    EmailAddress emailAddress = new EmailAddress(user, email);
    emailAddress.setMain(false);
    emailAddress.setValidated(false);
    emailAddressDao.insert(emailAddress);
    this.initiateEmailValidation(emailAddress);
    return emailAddress;
}

该经理调用的 DAO:

...

@PersistenceUnit
private EntityManagerFactory entityManagerFactory;

protected final EntityManager getEntityManager() {
    return entityManagerFactory.createEntityManager();
}

public boolean insert(Entity o) {
    o.setCreated(new Date());
    this.getEntityManager().persist(o);
    this.getEntityManager().flush();
    return true;
}

我尝试了不同的变体。最初,DAO 和 Manager 方法都用 @Transactional(propagation=REQUIRED); 注释,这就是它与纯 Hibernate 一起工作的方式。我试过删除传播设置,只注释 Manager 方法,只注释 DAO 方法......没有任何效果。

有什么想法吗? HibernateTransactionManagerJpaTransactionManager 之间似乎有一些根本不同。

【问题讨论】:

    标签: java spring hibernate jpa transactions


    【解决方案1】:
    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;
    
    protected final EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }
    

    问题是您自己创建了一个实体管理器,不要。只需注入EntityManager 而不是EntityManagerFactory 并使用@PersistenceContext 而不是@PersistenceUnit 进行注释。 Spring 将负责使其绑定到当前事务。

    @PersistenceContext
    private EntityManager entityManager;
    
    protected final EntityManager getEntityManager() {
        return entityManger;
    }
    

    如果您真的想继续注入EntityManagerFactory,请使用EntityManagerFactoryUtilsgetTransactionalEntityManager 方法来获取Spring 管理的EntityManager 实例。

    protected final EntityManager getEntityManager() {
         return EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory);
    }
    

    此外,它与“普通”hibernate 一起工作的事实并不意味着您的设置必须正确。你提到你使用了HibernateTemplate,它基本上可以在没有适当的事务设置的情况下工作,因为它会为手头的操作启动一个新的事务。所以很可能是应用程序似乎在实际上没有正常工作的地方正常工作。也许您有多个您期望的交易(来自服务层)。

    另一个注意事项是您的代码可能很危险

    public boolean insert(Entity o) {
        o.setCreated(new Date());
        this.getEntityManager().persist(o);
        this.getEntityManager().flush();
        return true;
    }
    

    在您的情况下,这可能会导致创建 2 个不同的 EntityManagers,因此您可能一直在刷新另一个,因为您坚持这样做。旁边您不应该调用 flush,因为这将完成在交易结束前。

    【讨论】:

    • 就是这样;谢谢。我没有意识到我每次都在创建一个新的 EntityManager,但现在这很有意义。此外,关于 HibernateTemplate 工作的公平点不是“正确”设置的证明。虽然,尤其是在propagation=REQUIRED 的情况下,嵌套事务方法应该 完全没问题,并且只会产生一个事务。我确实读过 Spring 事务传播与 JPA 事务管理器的行为不同。
    【解决方案2】:

    你需要用@PersistenceContext注解直接注入EntityManager,而不是PersistenceUnit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-12
      • 2011-06-29
      • 2021-07-23
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多