在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
答案 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()
}
equals()
和hashcode()
方法。@IdClass(UserPK.class)
@Id
注释声明ID字段