gpt4 book ai didi

hibernate - 如何在@Embeddable 中使用@GeneratedValue 作为复合主键?

转载 作者:行者123 更新时间:2023-12-05 09:34:42 25 4
gpt4 key购买 nike

我的数据库中有一个包含主复合键的表,当我使用 Hibernate 对其建模时,我使用 @EmbeddedId@Embedable。此复合主键的一列具有生成的值 @GeneratedValue(strategy = GenerationType.IDENTITY)

当我尝试在我的数据库中创建两个新对象时,出现如下错误:

org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [MyPackage#MyEmbedableClass [MyGeneratedPrimaryKeyValue=null, OtherPrimaryKey=21]]

但是当我查看我的数据库时,我的对象已经创建了。我不明白我的错误,我不知道如何解决我的问题。

我找到了一些类似我的主题,但还没有找到问题的答案。

  1. first exemple

  2. second exemple

  3. third exemple

@Entity(name = "Certification")
@Table(name = "CERTIFICATION")
public class Certification implements Serializable {

static final long serialVersionUID = -4399907743392740963L;

@EmbeddedId
private CertificationPK certificationPK;

// Others variables
// constructors
// Getter / Setter
// toString
// hashCode / equals
}

@Embeddable
public class CertificationPK implements Serializable {

private static final long serialVersionUID = 1433990897506209802L;

// MyGeneratedPrimaryKeyValue=null when I create
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull
@Column(name = "CERTIFICATION_ID")
private Integer certificationId;

// Other variable
// constructors
// Getter / Setter
// toString
// hashCode / equals
}

预先感谢您的帮助。

最佳答案

  1. 看起来您不能将 @GeneratedValue@EmbeddedId 一起使用。您可以在 this article 中找到一些解决方法但它对我来说效果不佳。

  2. this 中所述文档部分,应该可以将 @GeneratedValue@IdClass 一起使用。但是,由于 HHH-9662,它不起作用.

  3. this 中所述文档部分:

When using composite identifiers, the underlying identifier properties must be manually assigned by the user.

Automatically generated properties are not supported to be used to generate the value of an underlying property that makes the composite identifier.

Therefore, you cannot use any of the automatic property generator described by the generated properties section like @Generated, @CreationTimestamp or @ValueGenerationType or database-generated values.

Nevertheless, you can still generate the identifier properties prior to constructing the composite identifier.

关于hibernate - 如何在@Embeddable 中使用@GeneratedValue 作为复合主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66370320/

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