gpt4 book ai didi

java - 尝试级联持久子实体时出现 PersistenceException

转载 作者:行者123 更新时间:2023-11-29 08:33:12 24 4
gpt4 key购买 nike

我有 2 个实体:

大师:

@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;


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

}

子大师:

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

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

private String subName;


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

}

当我尝试通过设置 SubMaster 实体来保留 Master 实体时,出现以下异常:

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

然而,我希望 Hibernate 在持久化父实体时自动持久化子实体。

最佳答案

首先你反转了关联的所有者,因为我认为 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;

}

您告诉您的子实体获取父实体的 ID

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

-1.0 你几乎陷入困境,因为你被迫将 @Id 放在基本注释上,所以你需要将 id 和关系列分开,问题是 @GeneratedValue 强制先保存parent,然后在保存前手动设置id给child

引用:https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships

关于java - 尝试级联持久子实体时出现 PersistenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46233799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com