简体   繁体   English

org.hibernate.MappingException - 复合 id

[英]org.hibernate.MappingException - composite id

In my Spring boot - JPA application, I am trying to implement composite key :在我的 Spring boot - JPA 应用程序中,我试图实现复合键:

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

This gives me error, saying :这给了我错误,说:

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

Even if I implement Serializable it gives me error.即使我实现了Serializable它也会给我错误。

How can I resolve this ?我该如何解决这个问题?

Used : Spring + JPA + H2使用:弹簧 + JPA + H2

Composite Key can be created with @IdClass as below.复合键可以使用@IdClass创建,如下所示。
User.class用户类

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

UserPK.class用户PK.class

public class UserPK {
    private String timeStamp;
    private String firstName;
    private String lastName;
// constructors
// getters and setters
//implement euquels() and hashcode()
}
  1. Define a Class for primary key with all keys as fields.定义一个主键类,所有键作为字段。
  2. Implement equals() and hashcode() methods.实现equals()hashcode()方法。
  3. Annotate User class with @IdClass(UserPK.class)使用@IdClass(UserPK.class)注释用户类
  4. Declare Id fields with @Id annotation使用@Id注释声明 Id 字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM