org.hibernate.MappingException-复合ID

时间:2019-12-06 08:49:15

标签: java spring spring-boot jpa spring-data-jpa

在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,它也会给我带来错误。

我该如何解决?

已使用:Spring + JPA + H2

1 个答案:

答案 0 :(得分:2)

可以使用@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

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. 注释用户类
  5. 使用@Id注释声明ID字段