JPA with JTA: Persist entity and merge cascaded child entities

前端 未结 4 1631
情歌与酒
情歌与酒 2020-12-20 11:21

I have a bidirectional one-to-many relationship with the following entity classes:

0 or 1 client <-> 0 or more product orders

When persis

4条回答
  •  猫巷女王i
    2020-12-20 12:10

    Hi i had the same problem today, i ask to the openJPA mailing list with this email:

    Hi. I have a problem with insert and updating a reference in the same entity.

    Im trying to insert a new object (Exam) that has a reference to another object (Person) and at the same time i want to update an attribute (birthDate) of the Person object. The update never happens although i set CascadeType to ALL. The only way this works is doing a persist and after that a merge operation. Is this normal? Do i have to change something??

    I dont like the idea of a "manual update" using merge in the Person object because i don't know how many objects (child object of Exam) the user want to update.

    Entities:

    public class Exam{  
       @ManyToOne(cascade= CascadeType.ALL)
       @JoinColumn(name = "person_id")
       public Person person;
    ......
    }
    
    public class Person{
        private Date birthDate;
       @OneToMany(mappedBy = "person")
        private List exams
    .......
    }
    
    public class SomeClass{
       public void someMethod(){
          exam = new Exam()
          person.setBirthDate(new Date());
          exam.setPerson(person); 
          someEJB.saveExam(exam);
       }
    }
    
    public class someEJB(){
    
       public void saveExam(Exam exam){
            ejbContext.getUserTransaction().begin();
            em.persist(exam);
            //THIS WORKS
            em.merge(exam.getPerson());
            ejbContext.getUserTransaction().commit();       
       }
    
    }
    

    Do i have to use the MERGE method for every child object?

    And the answer was this:

    It looks like your problem is that the Exam is new, yet the Person is existing and the existing Entity gets ignored when cascading the persist operation. I believe this is working as expected.

    As long as your relationships are set to CascadeType.ALL, you could always change your em.persist(exam); to em.merge(exam);. That would take care of persisting the new exam, and it would also cascade the merge call to the person.

    Thanks, Rick


    I hope this can help you.

提交回复
热议问题