尝试级联持久化子实体

时间:2017-09-15 07:13:37

标签: java hibernate jpa persistence

我有两个实体:

@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "seq")
    private Integer seq;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "seq", referencedColumnName = "seq")
    private SubMaster subMaster;


    ...................

}

Sub Master:

@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {

    @Id
    @Column(name = "seq")
    private Integer seq;

    private String subName;


    ...................

}

当我试图通过设置Master实体来持久化SubMaster实体时,我会遇到以下异常:

javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned beforeQuery calling save(): SubMaster

然而,我期待Hibernate会在父实体被持久化时自动持久保存子实体。

2 个答案:

答案 0 :(得分:2)

为SubMaster添加@GeneratedValue(strategy = IDENTITY),看起来像SubMaster的id生成了异常

答案 1 :(得分:2)

首先,你颠倒了协会的所有者,因为我认为subMaster应该有@JoinColumn注释。

现在解决方案

取决于JPA版本:

-2.0您可以在关系注释上定义@Id注释,这样您就可以使用

@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "seq")
    private Integer seq;

    @OneToOne(mappedBy = "master", cascade = CascadeType.ALL)
    private SubMaster subMaster;

}

@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {

    @Id
    @JoinColumn(name = "seq", referencedColumnName = "seq")
    @OneToOne
    private Master master;

    private String subName;

}

你告诉你的孩子实体取父母的身份

master.setSubMaster(subMaster);
subMaster.setMaster(master)

-1.0你几乎被卡住,因为你被迫将@Id放在一个基本的注释上,所以你需要将一个id和一个关系列分开,问题是@GeneratedValue你是强制首先保存父项,然后在保存

之前手动将id设置为子项

参考:https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships