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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With