Search code examples
javajpamany-to-manyeclipselink

How to create a PK class which has a relation to a composite Id


I changed my Entity A's Id to a composite Id. Entity B also has a PK class which one side of the relation is Entity A. how should I change my PK class code? should I use IdClass instead of Id?

public class BPK implements Serializable{

    // I need to change this single Id to a composite Id to include 2 columns from Entity A instead of only one id attribute 
    @Id
    @Column(name = "aid")
    private Integer a;

    @Id
    @Column(name = "bid")
    private Integer b;

}

Class A PK

public class APK implements Serializable{

    @Id
    @Column(name = "id")
    private Integer id;

    @Id
    @Column(name = "project_mode")
    private Integer project;
 }

Solution

  • public class BPK implements Serializable{
        private APK a;
        private Integer b;
    
    }
    

    Primary key classes in JPA do not require annotations as they are mapped directly in the entity already. Derived IDs are the one place the specification allows nesting within primary keys, as the nested classes always drill down to basic types (vs entities).