创建时的Hibernate问题OnetoMany,ManyToOne Mapping给予null

时间:2014-12-04 09:56:22

标签: java hibernate null one-to-many many-to-one

我有一个这样的模型:

@Entity
[...]
class ParentObject{
    [...]
    @OneToMany(cascade = CascadeType.ALL, mappedBy= "parentObject", orphanRemoval = true)
    private List<Relationship> relationship;
}

并在关系实体中:

@ManyToOne
@JoinColumn(name="PARENT_OBJECT_ID")
private ParentObject parentObject;

一切正常,更新和保存。只有当我尝试创建一个新的ParentObject并在其中包含新的Relationships时:

parentObject: { 
  id: null, 
  relationship: [ 
      {id:null,
      parentObjectId:null,
      [...]
  }] 
}

hibernate没有ParentObject的id,因此Relationship.parentObject.id为null。数据库抛出错误说:

  

无法插入NULL(“MYDB”。“RELATIONSHIP”。“PARENT_OBJECT_ID”)

任何帮助都将不胜感激。

修改:这是我的服务代码:

public ParentObjectDto save(ParentObjectDto parentObjectDto) {
ParentObject parentObject = dtoConverter.convert(parentObjectDto, ParentObject.class);      

boolean isNewPO = parentObject.getId() == null ? true : false;

parentObject = parentObjectRepository.save(parentObject);

if (isNewPO) {
    // This loop ensures that when a new PO is added, the child relationship
    // objects are connected with the new parentObject that was just added.
    for (Relationship relationship : parentObject.getRelationship()) {
        relationship.setParentObject(parentObject);
    }
}

return dtoConverter.convert(parentObject, ParentObjectDto.class);

}

当然这些名字不是我在这里写的,我只是将它们改为更容易理解,如果我有任何拼写错误,那就是我的手动更改:)

1 个答案:

答案 0 :(得分:1)

查看代码时,问题可能是isNewPO为真时首先保存PO,然后将该父对象设置为关系。这意味着在保留PO时,关系没有设置PO,导致NULL插入PARENT_OBJECT_ID列(由于cascade = CascadeType.ALL,此时关系也会保留)。

要解决此问题,请在循环后移动parentObject = parentObjectRepository.save(parentObject);,或在dtoConverter.convert()中连接PO及其关系。