具有复合子键的单向OneToMany,而不是传播父ID

时间:2017-11-07 15:17:04

标签: java hibernate

我有以下2个参与者:

@Entity
@Table(name = "PARENT")
public class ParentEntity{
    @Id
    @Column(name = "PARENT_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dtvSeq")
    @SequenceGenerator(name = "dtvSeq", sequenceName = "PARENT_ID_SEQ")
    private Long parentId;

    @OneToMany(mappedBy = "childEntityPk.parentId", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    Collection<ChildEntity> childrenEntities;

    //getters and setters ommited

}

带有组合主键的子实体部分引用Parent_id(fk):

@Entity
@Table(name = "CHILDREN")
public class ChildEntity {
    @EmbeddedId
    private ChildEntityPk childEntityPk;

    //other fields
    //getter and setters ommited

    @Embeddable
    private class ChildEntityPk implements Serializable{
        long parentId;
        String name;
    }
}

它非常适合获取数据。但是,如果我想一次性持有ParentEntity及其子实体,我会从Oracle获得异常。

抛出此异常是因为hibernate没有更新childEntity.childEntityPk.parentId并且正在尝试插入null。

我也和@JoinColumn一起玩过但没有成功。

我不想要双向映射。

1 个答案:

答案 0 :(得分:0)

你有addChild()方法还是只更新集合?我建议

public void addChild(ChildEntity child) {
     child.setChildEntityPk(this.parentId, "name");
     childrenEntities.add(child);
}