Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

EclipseLink/Bugs/256277

< EclipseLink‎ | Bugs
Revision as of 22:03, 11 January 2009 by Michael.obrien.oracle.com (Talk | contribs) (Bug Analysis Document: 256277: Endless loop on @PrePersist using a nested Persist)

Bug Analysis Document: 256277: Endless loop on @PrePersist using a nested Persist


Document History

Date Author Version Description & Notes
20080105 Michael O'Brien 1.0 Initial reproduction use cases
20080111 Michael O'Brien 1.1 Simplify reproduction for flush on query

Overview

This bug describes the behavior and fix for the issue of nested flush() calls when using the @PrePersist annotation callback method on an unmanaged entity containing a read query method that causes a flush() when the entity is the target of a relationship from a managed entity that has pending changes.

This bug is also encountered when a secondary persist is executed inside of a @PrePersist callback method on the Entity being itself persisted. Soo there are two use cases here - we will concentrate on the read query causing a secondary flush to sync changes before the read - causing an infinite loop or double persist which causes a PK conflict.

Concepts

See p.139 of Pro EJB 3.0 "Some providers will flush the persistence context to ensure that the query incorporates all pending changes" - EclipseLink is one of these providers.

JPA Specification Notes

Here is what the JPA specification says about performing persists inside the @PrePersist method. Essentially it states that we should not be performing persists inside a @PrePersist callback - however it may be the responsibility of the container to handle any that may be done depending on the nature of the persistence.

JPA 1.0 Specification

  • P58 Section 3.5
    • "In general, portable applications should not invoke EntityManager or Query operations, access other entity instances, or modify relationships in a lifecycle callback method.[19]"
    • "[19] The semantics of such operations may be standardized in a future release of this specification."

JPA 2.0 Specification

  • P82 Section 3.5.1
    • "In general, portable applications should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context.[34] A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked."
    • "[34] The semantics of such operations may be standardized in a future release of this specification."

Reproduction

Prerequisites

  • Run tests out of container on an SE persistence unit (EE can also be used)
  • At least two entities must be persisted to avoid performance optimization code for a single entity
  • Two different entity classes are required
    • One must be managed, the other one containing the @PrePersist must be unmanaged/detached but referenced by the first
  • Test must commit more than one object so that the non-performance else clause in CommitManager.commitAllObjectsWithChangeSet() is used
  • Test must perform a change on an existing object that is already persisted
  • cascade must be set to CascadeType.ALL
  • fetch must be set to FetchType.EAGER
  • Set FlushMode to AUTO
    • entityManager.setFlushMode(FlushModeType.AUTO);

Data Model

This matches the data model used in Chapter 5 of Pro EJB 3.0.

@Entity
public class Employee implements Serializable {
    @Id
    private BigInteger id;
 
    @OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
    ParkingSpace parkingSpace;
 
    @OneToMany(fetch=FetchType.EAGER, mappedBy="employee", cascade=CascadeType.PERSIST)
    Collection<Phone> phones;
 
    @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
    Address address;
}
 
@Entity
public class Address implements Serializable {
 
    @Id
    private BigInteger id;
 
    @OneToMany(fetch=FetchType.EAGER, mappedBy="address",cascade=CascadeType.PERSIST)
    Collection<Employee> employees;
 
    @PrePersist
    // 256277: test prePersist with a nested persist
    public void prePersist() {
        name = "name"; 
        // get a reference to the entityManager and perform a persist inside this prePersist
        EntityManager entityManager = TestClient.staticEntityManager;
        processQuery(entityManager);
    }
}
 
@Entity
public class ParkingSpace implements Serializable {
    @Id
    private BigInteger id;
}
 
@Entity
public class Phone implements Serializable {
    @Id
    private BigInteger id;
 
    @ManyToOne
    Employee employee;
}
 
===Use Case 1: Persist unmanaged entity (with @PrePersist query) referenced by managed entity===
 
 
===Use Case 2: Persist other Entity (with its own @PrePersist and persist) inside @PrePersist callback ===
[https://bugs.eclipse.org/bugs/attachment.cgi?id=121567 Source]
 
 
This use case currently causes an infinite loop on the following line up to build 20090105.
<source lang="java">
    EntityClassListener(EntityListener).prePersist(DescriptorEvent) line: 412

Use Case 3: Persist other Entity (with a @PrePersist without a persist) inside @PrePersist callback

Source


The @PrePersist of the first entity will cause a persist of the second entity that also has it's own @PrePersist (but without another persist).

Normal functionality with no infinite loop.

Use Case 4: Persist other Entity (without its own @PrePersist) inside @PrePersist

Normal functionality with no infinite loop.

Analysis Constraints

Design / Functionality

Alternative 1: No flush() within a flush()

We will not perform nested flush() calls, a break will be required and a warning will printed if the entityManager is in FlushModeType.AUTO.

Testing

Use Case 1: Output of infinite loop

The following logs and stacktrace illustrate the current infinite loop behavior when performing a @PrePersist inside a @PrePersist as a result of a persist in this callback method.

Client Code

Client code is persisting 2 Cell entities that themselves persist new Cell entities in their @PrePersist method.

    private void processInsert() {
        // create 2 cells (to avoid performance optimization for 1 entity)  and link them
        Cell cell1 = new Cell();
        Cell cell2 = new Cell();
        cell1.setLeft(cell1);
        cell1.setRight(cell1);
        cell2.setLeft(cell2);
        cell2.setRight(cell2);
        try {
            getEntityManager().getTransaction().begin();
            getEntityManager().persist(cell1);
            getEntityManager().persist(cell2);            
            getEntityManager().flush();
            getEntityManager().getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }

Entity @PrePersist callback code

The @PrePersist code is the same as the entity requirements above and UC2 except that we persist Cell entities which contain a nested persist in their @PrePersist callback.

 
    @PrePersist
    // 256277: test prePersist with a nested persist
    public void prePersist() {
        setState("9999");
        // get a reference to the entityManager and perform a persist inside this prePersist
        EntityManager entityManager = TestClient.staticEntityManager;
        processInsert(entityManager);
    }
 
    /**
     * An infinite loop will occur if we persist Cell entities within this Cell.prePersist() as it contains a persist.
     * Normal functionality will occur if we persist Leaf entites (which do not contain a persist in their PrePersist callback)
     * @param entityManager
     */
    private void processInsert(EntityManager entityManager) {
        // create 2 cells (to avoid performance optimization for 1 entity)  and link them
        int numCells = 2;
        List<Cell> cells = new ArrayList<Cell>();
        //List<Leaf> cells = new ArrayList<Leaf>();
        for(int i=0; i < numCells; i++) {
            cells.add(new Cell());
            //cells.add(new Leaf());
        }
...

StackTrace

TestClient [Java Application]	
	org.eclipse.persistence.example.TestClient at localhost:2561	
		Thread [main] (Suspended (breakpoint at line 112 in Cell))	
			Cell.processInsert(EntityManager) line: 112	
			Cell.prePersist() line: 69	
			NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method]	
			NativeMethodAccessorImpl.invoke(Object, Object[]) line: 39	
			DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 25	
			Method.invoke(Object, Object...) line: 597	
			PrivilegedAccessHelper.invokeMethod(Method, Object, Object[]) line: 344	
			EntityClassListener(EntityListener).invokeMethod(Method, Object, Object[], DescriptorEvent) line: 297	
			EntityClassListener.invokeMethod(String, DescriptorEvent) line: 64	
			EntityClassListener(EntityListener).prePersist(DescriptorEvent) line: 412	
			DescriptorEventManager.notifyListener(DescriptorEventListener, DescriptorEvent) line: 650	
			DescriptorEventManager.notifyEJB30Listeners(DescriptorEvent) line: 593	
			DescriptorEventManager.executeEvent(DescriptorEvent) line: 187	
			RepeatableWriteUnitOfWork(UnitOfWorkImpl).registerNewObjectClone(Object, Object, ClassDescriptor) line: 3980	
			RepeatableWriteUnitOfWork(UnitOfWorkImpl).registerNotRegisteredNewObjectForPersist(Object, ClassDescriptor) line: 3959	
			RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(Object, ClassDescriptor) line: 336	
			RepeatableWriteUnitOfWork(UnitOfWorkImpl).registerNewObjectForPersist(Object, Map) line: 3903	
			EntityManagerImpl.persist(Object) line: 254	
			Cell.processInsert(EntityManager) line: 121	
			Cell.prePersist() line: 69	
...
			Cell.prePersist() line: 69	
			NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method]	
			NativeMethodAccessorImpl.invoke(Object, Object[]) line: 39	
			DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 25	
			Method.invoke(Object, Object...) line: 597	
			PrivilegedAccessHelper.invokeMethod(Method, Object, Object[]) line: 344	
			EntityClassListener(EntityListener).invokeMethod(Method, Object, Object[], DescriptorEvent) line: 297	
			EntityClassListener.invokeMethod(String, DescriptorEvent) line: 64	
			EntityClassListener(EntityListener).prePersist(DescriptorEvent) line: 412	
			DescriptorEventManager.notifyListener(DescriptorEventListener, DescriptorEvent) line: 650	
			DescriptorEventManager.notifyEJB30Listeners(DescriptorEvent) line: 593	
			DescriptorEventManager.executeEvent(DescriptorEvent) line: 187	
			RepeatableWriteUnitOfWork(UnitOfWorkImpl).registerNewObjectClone(Object, Object, ClassDescriptor) line: 3980	
			RepeatableWriteUnitOfWork(UnitOfWorkImpl).registerNotRegisteredNewObjectForPersist(Object, ClassDescriptor) line: 3959	
			RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(Object, ClassDescriptor) line: 336	
			RepeatableWriteUnitOfWork(UnitOfWorkImpl).registerNewObjectForPersist(Object, Map) line: 3903	
			EntityManagerImpl.persist(Object) line: 254	
			TestClient.processInsert() line: 176	
			TestClient.doQuery() line: 254	
			TestClient.main(String[]) line: 247	
	C:\jdk1.6.0\bin\javaw.exe (Jan 5, 2009 1:10:19 PM)	

Logs

[EL Finest]: 2009.01.05 13:09:22.915--UnitOfWork(2804823)--Thread(Thread[main,5,main])--assign sequence to the object (1,210 -> org.eclipse.persistence.example.business.Cell@11024915( id: null state: null left: null right: null))
[EL Finest]: 2009.01.05 13:09:22.915--UnitOfWork(2804823)--Thread(Thread[main,5,main])--PERSIST operation called on: org.eclipse.persistence.example.business.Cell@8180602( id: null state: null left: null right: null).
[EL Finest]: 2009.01.05 13:09:22.930--UnitOfWork(2804823)--Thread(Thread[main,5,main])--assign sequence to the object (1,211 -> org.eclipse.persistence.example.business.Cell@8180602( id: null state: null left: null right: null))
Exception in thread "main" java.lang.StackOverflowError
	at java.text.DecimalFormat.setMinimumIntegerDigits(DecimalFormat.java:2677)
	at java.text.SimpleDateFormat.zeroPaddingNumber(SimpleDateFormat.java:1184)
	at java.text.SimpleDateFormat.subFormat(SimpleDateFormat.java:1125)
	at java.text.SimpleDateFormat.format(SimpleDateFormat.java:882)
	at java.text.SimpleDateFormat.format(SimpleDateFormat.java:852)
	at java.text.DateFormat.format(DateFormat.java:316)
	at org.eclipse.persistence.logging.AbstractSessionLog.getDateString(AbstractSessionLog.java:644)
	at org.eclipse.persistence.logging.AbstractSessionLog.getSupplementDetailString(AbstractSessionLog.java:654)
	at org.eclipse.persistence.logging.DefaultSessionLog.log(DefaultSessionLog.java:130)
	at org.eclipse.persistence.internal.sessions.AbstractSession.log(AbstractSession.java:2492)
	at org.eclipse.persistence.internal.sessions.AbstractSession.log(AbstractSession.java:3579)
	at org.eclipse.persistence.internal.sessions.AbstractSession.log(AbstractSession.java:3551)
	at org.eclipse.persistence.internal.sessions.AbstractSession.log(AbstractSession.java:3527)
	at org.eclipse.persistence.internal.sessions.AbstractSession.log(AbstractSession.java:3449)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.logDebugMessage(UnitOfWorkImpl.java:5106)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:3945)
	at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:336)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3903)
	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:254)
	at org.eclipse.persistence.example.business.Cell.processInsert(Cell.java:121)
	at org.eclipse.persistence.example.business.Cell.prePersist(Cell.java:69)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.eclipse.persistence.internal.security.PrivilegedAccessHelper.invokeMethod(PrivilegedAccessHelper.java:344)
	at org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListener.invokeMethod(EntityListener.java:297)
	at org.eclipse.persistence.internal.jpa.metadata.listeners.EntityClassListener.invokeMethod(EntityClassListener.java:64)
	at org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListener.prePersist(EntityListener.java:412)
	at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:650)
	at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:593)
	at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:187)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:3980)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:3959)
	at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:336)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3903)
	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:254)
	at org.eclipse.persistence.example.business.Cell.processInsert(Cell.java:121)
	at org.eclipse.persistence.example.business.Cell.prePersist(Cell.java:69)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.eclipse.persistence.internal.security.PrivilegedAccessHelper.invokeMethod(PrivilegedAccessHelper.java:344)
	at org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListener.invokeMethod(EntityListener.java:297)
	at org.eclipse.persistence.internal.jpa.metadata.listeners.EntityClassListener.invokeMethod(EntityClassListener.java:64)
	at org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListener.prePersist(EntityListener.java:412)
	at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:650)
	at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:593)
	at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:187)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:3980)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:3959)
	at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:336)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3903)
	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:254)
	at org.eclipse.persistence.example.business.Cell.processInsert(Cell.java:121)
	at org.eclipse.persistence.example.business.Cell.prePersist(Cell.java:69)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)

Use Case 2: Output normal

The following logs and stacktrace illustrate the current normal behavior when performing a @PrePersist inside a @PrePersist callback that has no nested persist.

Entity @PrePersist callback code

The @PrePersist code is the same as UC1 except that we persist Leaf entities which do not have a persist in their @PrePersist callback.

 
    @PrePersist
    // 256277: test prePersist with a nested persist
    public void prePersist() {
        setState("9999");
        // get a reference to the entityManager and perform a persist inside this prePersist
        EntityManager entityManager = TestClient.staticEntityManager;
        processInsert(entityManager);
    }
 
    /**
     * An infinite loop will occur if we persist Cell entities within this Cell.prePersist() as it contains a persist.
     * Normal functionality will occur if we persist Leaf entites (which do not contain a persist in their PrePersist callback)
     * @param entityManager
     */
    private void processInsert(EntityManager entityManager) {
        // create 2 cells (to avoid performance optimization for 1 entity)  and link them
        int numCells = 2;
        //List<Cell> cells = new ArrayList<Cell>();
        List<Leaf> cells = new ArrayList<Leaf>();
        for(int i=0; i < numCells; i++) {
            //cells.add(new Cell());
            cells.add(new Leaf());
        }
...

StackTrace

Logs

[EL Finer]: 2009.01.05 15:33:57.746--ClientSession(12213370)--Connection(7896426)--Thread(Thread[main,5,main])--begin transaction
[EL Finest]: 2009.01.05 15:33:57.746--UnitOfWork(5998631)--Thread(Thread[main,5,main])--Execute query InsertObjectQuery(org.eclipse.persistence.example.business.Cell@10040532( id: 2551 state: 9999 left: 2551 right: 2551))
[EL Finest]: 2009.01.05 15:33:57.746--UnitOfWork(5998631)--Thread(Thread[main,5,main])--Execute query WriteObjectQuery(org.eclipse.persistence.example.business.Cell@10040532( id: 2551 state: 9999 left: 2551 right: 2551))
[EL Fine]: 2009.01.05 15:33:57.746--ClientSession(12213370)--Connection(7896426)--Thread(Thread[main,5,main])--INSERT INTO EL_CELL (ID, STATE, TSEQ, RIGHT_ID) VALUES (?, ?, ?, ?)
	bind => [2551, 9999, null, null]
[EL Fine]: 2009.01.05 15:33:57.746--ClientSession(12213370)--Connection(7896426)--Thread(Thread[main,5,main])--UPDATE EL_CELL SET STATE = ?, RIGHT_ID = ? WHERE (ID = ?)
	bind => [9999, 2551, 2551]
[EL Finest]: 2009.01.05 15:33:57.746--UnitOfWork(5998631)--Thread(Thread[main,5,main])--Execute query InsertObjectQuery(org.eclipse.persistence.example.business.Leaf@9470766( id: 1003 state: 0000 left: 1003 right: 1003))
[EL Finest]: 2009.01.05 15:33:57.746--UnitOfWork(5998631)--Thread(Thread[main,5,main])--Execute query WriteObjectQuery(org.eclipse.persistence.example.business.Leaf@9470766( id: 1003 state: 0000 left: 1003 right: 1003))
[EL Fine]: 2009.01.05 15:33:57.746--ClientSession(12213370)--Connection(7896426)--Thread(Thread[main,5,main])--INSERT INTO EL_LEAF (ID, STATE, TSEQ, RIGHT_ID) VALUES (?, ?, ?, ?)
	bind => [1003, 0000, null, null]
[EL Fine]: 2009.01.05 15:33:57.746--ClientSession(12213370)--Connection(7896426)--Thread(Thread[main,5,main])--UPDATE EL_LEAF SET STATE = ?, RIGHT_ID = ? WHERE (ID = ?)
	bind => [0000, 1003, 1003]
[EL Finer]: 2009.01.05 15:33:57.761--UnitOfWork(5998631)--Thread(Thread[main,5,main])--begin unit of work commit

API

GUI

Config files

Documentation

Open Issues

Issue # Owner Description / Notes
I1 mobrien Verify that Entity containing the @PrePersist callback has been registered

Decisions

Issue # Description / Notes Decision

Future Considerations

During the research for this bug, the following items were identified as out of scope but are captured here as potential future enhancements. If agreed upon during the review process these should be logged in the bug system.

References

Copyright © Eclipse Foundation, Inc. All Rights Reserved.