在我的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
可以用@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字段