JPA单向OneToMany从JSON插入或更新Parent with Children

时间:2016-08-16 15:03:38

标签: java hibernate jpa persistence

我想编写在父数据库中不存在的情况下插入父对象及其子对象的方法,或者当对象不为空时更新它。

例如:

@Entity
public class Parent {
    @Id
    @Column(name = "PARENT_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column
    private String property;

    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID")
    private Set<Child> children;
    // getters and setters
}

@Entity
public class Child{
    @Id
    @Column(name = "CHILD_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column
    private String property;

    @Column(name="PARENT_ID")
    private Integer parentId;
    // getters and setters
}

这是我用于插入的代码,它工作正常:

@Transactional
public Parent save(Parent parent) {
    Set<Child> children = parent.getChildren();
    parent.setChildren(null);
    Parent mergedParent = entityManager.merge(parent);
    for(Child child : children) {
        child.setParentId(mergedParent.getId());
    }
    mergedParent.setChildren(children);
    return mergedParent;
}
使用JSON的杰克逊对父母进行反序列化:

{
  "property": "some val",
  "children": [
    {
      "property": "some val"
    },
    {
      "property": "some val"
    },
    {
      "property": "some val"
    }
  ]
}

Save方法返回id = 1的父对象和parentId = 1且id为1到3的子对象 - Parent及其子节点现在在数据库中。

在事务之外的一些更改后,我传递给以前返回的保存方法Parent:

{
  "id": 1,
  "property": "changed val",
  "children": [
    {
      "id": 1,
      "property": "some val",
      "parentId": 1
    },
    {
      "id": 2,
      "property": "some val",
      "parentId": 1
    },
    {
      "id": 3,
      "property": "changed val",
      "parentId": 1
    },
    {
      "property": "new child val"
    }
  ]
}

我收到异常(父实体存在于数据库中,有些孩子存在,有些孩子不存在):

detached entity passed to persist: Child

我应该如何处理这种情况?

0 个答案:

没有答案