保存具有OneToMany关系的模型

| 你好 我有这样的模型:
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;
}
我的控制器中有一个像这样的方法:
public static void savePerson(Person person) {
    person.save();
    renderJSON(person);
}
我的问题是,当我尝试使用savePerson()保存一个人时,出现此错误(仅当我的Person列表不为空时):
PersistenceException occured : org.hibernate.HibernateException: A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: models.Person.infos
我不明白该错误消息,因为如果列表以前为空,则该错误消息会出现。     
已邀请:
我今天有一个非常相似的问题。 问题在于您不能仅将新的Collection分配到\'infos \'列表,因为这样Hibernate就会感到困惑。当您在控制器中使用“人”作为参数时,“播放”会自动执行此操作。为了解决这个问题,您需要修改\'infos \'的getters和setters,以便它不会实例化新的Collection / List。 这是我到目前为止找到的最简单的解决方案:
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);
}
    

要回复问题请先登录注册