fonji
fonji

Reputation: 162

Creating Composite Primary Key in Child Class (JPA)

Suppose I have the following situation between a parent class and child class:

Class Parent {
    @Id
    @Column(name="product")
    Long product;

    //more fields.
}

Class Child extends Parent {
    @Column(name="type")
    String productType;

    @Column(name="version")
    int version;

    //more fields.
}

Is it possible to to have a composite primary key in the Child class even though the Child Class extends the Parent which already has a primary key?

Upvotes: 0

Views: 1123

Answers (1)

Jeff Wang
Jeff Wang

Reputation: 1867

The short answer is no. In JPA, you can not redefine primary keys. If your parent class has an @ID annotation, no subclass would allow @ID annotations regardless of inheritance strategy.

The longer answer is that if you need to do something like this, you should re-think your object mapping and your inheritance strategy. If you have a parent that already has a uniquely identifiable set of fields, why are you looking to have a child that breaks this convention? And even if you succeed, is this a safe thing for you to do in terms of architecture and code clarity?

Upvotes: 1

Related Questions