Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Inheritance demands ID in subclass

I have a problem with my jpa domain model. I am just trying to play around with simple inheritance for which I use a simple Person base-class and and a Customer subclass. According to the official documentation (both, JPA and EclipseLink) I only need the ID-attribute/column in the base-class. But when I run my tests, I always get an error telling me that Customer has no @Id?

First I thought the problem lies in the visibility of the id-attribute, because it was private first. But even after I changed it to protected (so the subclass has direct access) it isnt working.

Person:

@Entity @Table(name="Persons") @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name = "TYPE") public class Person {      @Id     @GeneratedValue     protected int id;     @Column(nullable = false)     protected String firstName;     @Column(nullable = false)     protected String lastName; 

Customer:

@Entity @Table(name = "Customers") @DiscriminatorValue("C") public class Customer extends Person {      //no id needed here 

I am running out of ideas and resources to look at. It should be a rather simple problem, but I just dont see it.

like image 705
lostiniceland Avatar asked Sep 12 '09 16:09

lostiniceland


People also ask

Which JPA inheritance strategies require discriminator column?

Only SINGLE_TABLE inheritance hierarchies require a discriminator column and values. JOINED hierarchies can use a discriminator to make some operations more efficient, but do not require one. TABLE_PER_CLASS hierarchies have no use for a discriminator.

How does JPA inheritance work?

JPA Inheritence Overview Inheritence is a key feature of object-oriented programming language in which a child class can acquire the properties of its parent class. This feature enhances reusability of the code. The relational database doesn't support the mechanism of inheritance.

Why ID is mandatory in JPA?

Id is required by JPA, but it is not required that the Id specified in your mapping match the Id in your database. For instance you can map a table with no id to a jpa entity. To do it just specify that the "Jpa Id" is the combination of all columns.

Which inheritance strategy is better in Hibernate?

Keep in mind when using default JPA/Hibernate annotations, Hibernate always fetch all of subclasses. If you have a single hierarchy, prefer To use Single Table Inheritance strategy.


1 Answers

I solved it myself by creating a MappedSuperclass

@MappedSuperclass public abstract class EntityBase{    @Id    @GeneratedValue    private int id;     ...setter/getter } 

All entities are inheriting from this class. I am still wondering why the tutorials dont mention this, but maybe it gets better with the JPA 2 implementations.

like image 135
lostiniceland Avatar answered Sep 22 '22 19:09

lostiniceland