Search code examples
javajpaeclipselink

Why do I get shared Ids with JPA?


I've a question about JPA and Inheritance (EclipseLink) :

For a school project, I've created an abstract class : HumanEntity and different subclasses which implement it.

The abstract class:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class HumanEntity implements IHuman{

@Id
@GeneratedValue
protected long      id;

@Column(name = "FIRST_NAME")
protected String    firstName;

@Column(name = "LAST_NAME")
protected String    lastName;

protected LocalDate birthDate;

protected HumanEntity(){

}

@Override
public String getFirstName() {
    return firstName;
}

@Override
public String getLastName() {
    return lastName;
}

@Override
public LocalDate getBirthDate() {
    return birthDate;
}

}

A subclass example :

@Entity
@Table(name="ACTOR")
public class ActorEntity extends HumanEntity{

protected ActorEntity(){}

protected ActorEntity(ActorBuilder actorBuilder){
    this.firstName  = actorBuilder.getFirstName();
    this.lastName = actorBuilder.getLastName();
    this.birthDate  = actorBuilder.getBirthDate();
}

}

When I run the the project : -> Ids are shared for every subclasses then I have

In the Actor Table : 1 -> .... 3 -> ....

In the director table : 2 -> ....

How can I create a different Id for every subclasses but with a protected (shared) Id in my code ?

Another little question EclipseLink ,or JPA always create a sequence table but i dont know what is it used for ? can I delete it ?

Thanks a lot !


Solution

  • All objects that are of type HumanEntity or subclasses are instances of HumanEntity, hence the id's need to be consistent, and hence from the same "group" of ids.

    You CANNOT have say id 1 for an Actor and id 1 for a Director since they are both HumanEntity, and you need to uniquely identify a HumanEntity. i.e Actor#1 is also HumanEntity#1. So you cannot also have Director#1 since that would also be HumanEntity#1!

    If you want to have id's like those then you would need to change your inheritance structure.