【问题标题】:Save a model with a relation OneToMany保存具有关系 OneToMany 的模型
【发布时间】:2011-05-16 07:50:27
【问题描述】:

嗨 我有这样的模型:

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

我不理解错误消息,因为如果列表之前是否为空,它就会出现。

【问题讨论】:

  • 不行,因为我无法应用本文中的解决方案

标签: hibernate jpa playframework one-to-many


【解决方案1】:

我今天遇到了一个非常相似的问题。

问题是你不能仅仅将一个新的集合分配给“信息”列表,因为这样 Hibernate 会感到困惑。当您在控制器中使用 Person 作为参数时,Play 会自动执行此操作。要解决此问题,您需要修改“信息”的 getter 和 setter,以便它不会实例化新的 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-01
    • 2015-08-06
    • 2018-05-11
    • 2019-01-12
    • 2012-02-27
    • 2019-02-10
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多