views:

926

answers:

2

Hello Everyone

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.

+1  A: 

JPA knows two different ways to apply inheritance:

  • Joined table inheritance
  • Single table inheritance

With single table inheritance you will need a discriminator column to distinguish between the rows in the table.

With joined table inheritance, each class gets it's own table so no discriminator column is needed.

I think your problem is that you mixed the two concepts. So either:

  • define the discriminator columns and use `InheritanceType.SINGLE_TABLE` and don't use `@Table` on subclasses
  • or use `InheritanceType.JOINED` but don't specify the discriminator column and values!
Tom van Zummeren
I tried it, but still the same problem. Also, according to http://en.wikibooks.org/wiki/Java_Persistence/Inheritance#Joined.2C_Multiple_Table_Inheritance you can use the discriminator
lostiniceland
+1  A: 

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.

lostiniceland
+1. I believe this is the correct answer to your specific question.
Hosam Aly
Thanks for the comment. I still wasnt sure about that.
lostiniceland