簡體   English   中英

如何在@Embeddable 中使用@GeneratedValue 作為復合主鍵?

[英]How to use @GeneratedValue inside @Embeddable used as composite primary key?

我的數據庫中有一個帶有主復合鍵的表,當我使用 model 和 Hibernate 時,我使用@EmbeddedId@Embedable 此復合主鍵的一列具有使用@GeneratedValue(strategy = GenerationType.IDENTITY)生成的值。

當我嘗試在我的數據庫中創建兩個新的 object 時,出現如下錯誤:

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

但是當我查看我的數據庫時,我的對象已經創建。 我不明白我的錯誤,我不知道如何解決我的問題。

我找到了一些類似我的主題,但我還沒有找到我的問題的答案。

  1. 第一個例子

  2. 第二個例子

  3. 第三個例子

@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一起使用。 您可以在本文中找到一些解決方法,但對我來說效果不佳。

  2. 正如節文檔中所述,應該可以將@GeneratedValue@IdClass一起使用。 但是,由於HHH-9662 ,它不起作用。

  3. 正如文檔的節所述:

使用復合標識符時,基礎標識符屬性必須由用戶手動分配。

不支持使用自動生成的屬性來生成構成復合標識符的基礎屬性的值。

因此,您不能使用生成的屬性部分描述的任何自動屬性生成器,例如@Generated@CreationTimestamp@ValueGenerationType或數據庫生成的值。

盡管如此,您仍然可以在構造復合標識符之前生成標識符屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM