Save the model with the OneToMany relationship

Hi I have such models:

public class Person extends Model {
...
    @OneToMany(orphanRemoval = true, mappedBy = "person")
    @Cascade({ CascadeType.ALL })
    public List<Contact> infos = new ArrayList<Contact>();
}

public class Contact extends Model {
...
   @ManyToOne(optional = false)
   public Person person;
}

And I have a method in my controller:

public static void savePerson(Person person) {
    person.save();
    renderJSON(person);
}

My problem is that when I try to save a person using savePerson (), I have this error (only if my Person list is not empty):

PersistenceException occured : org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: models.Person.infos

I do not understand the error message because it appears if the list was previously empty or not.

+3
source share
2 answers

Today I had a very similar problem.

, "infos", Hibernate . , Person . , "", /.

, :

public class Person extends Model {
// ... 
  public List<Contact> getInfos() {
    if (infos == null) infos = new ArrayList<Contact>();
    return infos;
  }

  public void setInfos(List<Contact> newInfos) {
    // Set new List while keeping the same reference
    getInfos().clear();  
    if (newInfos != null) {
      this.infos.addAll(newInfos);
    }
  }
// ...
}

:

public static void savePerson(Person person) {
    person.merge();
    person.save();
    renderJSON(person);
}
+1

. , .

0

All Articles