使用父子关系保存Hibernate实体失败,并显示外键错误

时间:2014-08-27 00:03:38

标签: java hibernate

我受到了侵犯 - 尝试保存Hibernate实体时找不到父密钥

我有父实体:

@Entity
@Table(name = "parents")
public class Parent implements Serializable {
    private static final long serialVersionUID = 1246376778314918671L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
    @SequenceGenerator(name = "seq", sequenceName = "PARENT_ID_SEQ", allocationSize = 1)
    @Column(name = "parent_id")
    private long parentId;

    @Column(name = "display_name")
    @Size(min = 1, max = 128)
    @NotBlank   
    private String displayName;

    @JsonManagedReference("childAssignments")
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval=true)
    private Set<ChildAssignment> childAssignments = new HashSet<ChildAssignment>(0);

    //regular getters and setters here
}

和子实体看起来像(在数据库中,它在parent表的parent_id字段上有外键):

Entity
@Table(name = "child_assignments")
public class ChildAssignment implements Serializable {
    private static final long serialVersionUID = -5949955576511639261L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
    @SequenceGenerator(name = "seq", sequenceName = "CHILD_ASSIGNMENT_ID_SEQ", allocationSize = 1)
    @Column(name = "child_assignment_id")
    private long childAssignmentId;

    @Column(name = "parent_id")  
    private long parentId;   // getting error because after creating new parent it has not been set

    @Column(name = "site_id")
    private long siteId;

    @ManyToOne
    @JoinColumn(name = "parent_id", insertable = false, updatable = false)
    private Parent parent;

    // regular getters and setters here

}

在创建父对象和childAssignments对象之后,我将childAssignment添加到父

ChildAssignment ca = new ChildAssignment();
ca.setSiteId(1);
// I do not set parent_id here since I do not know it and expecting Hibernate to figure it out

parent.getChildAssignments().add(childAssignment);
session.save(parent);

预期的结果是使用ID保存新的父条目,并在使用此id保存子项后,但似乎hibernate在保存时不知道parent_id,我应该如何构建我的关联以使其工作?或者在parent_id字段上有一些注释?

已更新

我试图在childAssignment实体上删除parent_id或将其设置为@Transient,并且得到新的错误无法在表中插入NULL,很明显Hibernate试图插入parent_id但不填充它,

为孩子设置父母也无济于事

ChildAssignment ca = new ChildAssignment();
   ca.setSiteId(1);
   ca.setParent(parent)

   parent.getChildAssignments().add(childAssignment);
   session.save(parent);

我缺少什么?

解决

我解决了更改childAssignment实体的问题

@Transient -- add transient (just to have it)
@Column(name = parent_id", insertable = false, updatable = false) -- add insertable and updatable  both equals to false
private parentId; 


.....

 @ManyToOne
 @JoinColumn(name = "parent_id") -- remove  insertable = false, updatable = false options
 private Parent parent;

1 个答案:

答案 0 :(得分:0)

你需要这样做:

ca.setParent(parent);

如果指定双面关系,则必须在Java代码中分配双方,就像它是纯Java一样。

其次,您宣布了一个父母的问题&#39;列是多余的。 Hibernate将自动为您创建。