简体   繁体   中英

org.hibernate.MappingException - composite id

In my Spring boot - JPA application, I am trying to implement composite key :

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

How can I resolve this ?

Used : Spring + JPA + H2

Composite Key can be created with @IdClass as below.
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. Define a Class for primary key with all keys as fields.
  2. Implement equals() and hashcode() methods.
  3. Annotate User class with @IdClass(UserPK.class)
  4. Declare Id fields with @Id annotation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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