簡體   English   中英

org.hibernate.MappingException - 復合 id

[英]org.hibernate.MappingException - composite id

在我的 Spring boot - JPA 應用程序中,我試圖實現復合鍵:

@Entity
public class User 
{
    @Id
    private String timeStamp;
    @Id
    private String firstName;
    @Id
    private String lastName;
}

這給了我錯誤,說:

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Composite-id class must implement Serializable: com.mua.testkeys.model.User

即使我實現了Serializable它也會給我錯誤。

我該如何解決這個問題?

使用:彈簧 + JPA + H2

復合鍵可以使用@IdClass創建,如下所示。
用戶類

@IdClass(UserPK.class)
@Table(name = "user")
@Entity
public class User {
    @Id
    private String timeStamp;
    @Id
    private String firstName;
    @Id
    private String lastName;
//remaining fields
// getters and setters
}

用戶PK.class

public class UserPK {
    private String timeStamp;
    private String firstName;
    private String lastName;
// constructors
// getters and setters
//implement euquels() and hashcode()
}
  1. 定義一個主鍵類,所有鍵作為字段。
  2. 實現equals()hashcode()方法。
  3. 使用@IdClass(UserPK.class)注釋用戶類
  4. 使用@Id注釋聲明 Id 字段

暫無
暫無

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

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