在EntityListener中插入导致Hibernate中的ConcurrentModificationException

时间:2016-02-21 11:05:36

标签: java spring hibernate jpa-2.1

我有一个实体监听器,用于查找所选实体的更改。

@PostUpdate
@PostPersist
void onChange(RhEntity data) {
    InjectHelper.getInstance().inject(this, this.changeService);
    if (ReflectionUtils.hasChangeListener(data.getClass()))
        changeService.persistAndNotifyAll(data, DataChange.DATA_CHANGE_TYPE_INSERT_OR_UPDATE);
}

当事务完成时,在提交时Hibernate会抛出ConcurrentModificationException

org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction

    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:526)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:521)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy106.add(Unknown Source)
    at com.rh.cores.architecture.tests.services.PersonDataUtils.getNaturalPerson(PersonDataUtils.java:65)
    at com.rh.cores.architecture.tests.services.PersonDataUtils.initPersonData(PersonDataUtils.java:92)
    at com.rh.cores.architecture.tests.services.PersonDataUtils$$FastClassBySpringCGLIB$$6b46a725.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    at com.rh.cores.architecture.tests.services.PersonDataUtils$$EnhancerBySpringCGLIB$$13329715.initPersonData(<generated>)
    at com.rh.cores.architecture.tests.units.DataChangeListenerTest.beforeMethod(DataChangeListenerTest.java:53)
    at com.rh.cores.architecture.tests.RhAuthenticatedTest.setup(RhAuthenticatedTest.java:45)
    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:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
Caused by: javax.persistence.RollbackException: Error while committing the transaction
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:86)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
    ... 50 more
Caused by: java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:558)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:61)
    ... 51 more

我用Spring配置hibernate,

**当我使用@Transactional(Transactional.TxType.REQUIRES_NEW)

时,此代码有效

2 个答案:

答案 0 :(得分:1)

JPA 2.1规范说(3.5.2):

  

以下规则适用于生命周期回调方法:

     

...

     
      
  • 生命周期   回调可以调用JNDI,JDBC,JMS和企业bean。实体   监听器和回调方法Java Persistence 2.1,
  •   
  • 在   一般来说,便携式应用程序的生命周期方法不应该   调用EntityManager或查询操作,访问其他实体   实例,或修改同一持久性内的关系   上下文[46]。 [47]生命周期回调方法可以修改   调用它的实体的非关系状态。
  •   

您无法真正更改此回调中托管对象的持久状态。

此外,Hibernate还有一个问题:HHH-7537。此问题已关闭,因为生命周期回调 - 与您的一样 - 并未遵循规范。你可以通过打开一个新事务来做这种事情(即使用Spring,在生命周期方法上使用public int getValeur(int x, int y) { Position p=new Position(x,y); Integer m=valeurs.get(p); if (m == null) { throw new IllegalArgumentException ("Invalid position " + x + "," + y); } return m; }

答案 1 :(得分:1)

我通过以下方法在Spring Framework应用程序中解决了我的问题:

@Service
@Transactional(propagation=Propagation.REQUIRES_NEW) //it means a new transaction will be created 
public class MyService {
 ...
}

@Component
public class MyListener {

    private static MyService myService;

@Autowired
    public void setMyService (MyService myService) {
        MyListener.myService= myService;
    }

    @PostUpdate
    public void myPostUpdate(MyEntity entity) {
//      entity.setModificationDate(new Date());
        myService.methodBar(entity.getBar());//calling some method
    }

    @PostPersist
    public void myPostPersist(MyEntity entity) {
        myService.methodFoo(entity.getFoo());//calling some method
    }  

}


@Entity
@Table(name= "TB_MY_ENTITY")
@DynamicUpdate
@EntityListeners(MyListener.class)
public class MyEntity {
    ....
}

我希望这会有所帮助!