1

Basically I have a similar issue as in this question: jpa how to create new entity with same id as parent entity (JOINED Inheritance)

But since that question is 9 years old, here is me hoping that today there is a solution to this problem.

Here is my Problem: I am using entity inheritance with inheritance type joined.

The entities are: 1. Person 2. Doctor (extends Person) 3. Professor (extends Person)

Here is my actual issue:

  • When I create a Doctor, the data is filled in tables Doctor and Person with the same id, lets say id = 1 ==> All is good so far

  • When I create a Professor, the data is filled in tables Professor and Person with the same id, lets say id = 2 ==> All still good so far

  • When an existing Doctor (id=1) now also becomes a Professor (or vice versa), I want the Person and Doctor to persist with the same id, and just add the entry in the table Professor, also with id=1.

Here is some code of how I try to make a Doctor also a Professor:

public void makeDocAlsoProf(id){

// Find existing Person
List<Person> persons = personRepo.findById(id);
Person foundPerson = !persons.isEmpty() ? persons.iterator().next() : null;

prof = new Professor(foundPerson); //This copies all parent Person fields
prof.setId(foundPerson.getId()); // Set the same id (id = 1)

prof = professorRepo.save(prof); // This gives Prof a new id (id = 3)
}

So before the execution of the method this is what rows I have in the database:

Person:

  • id 1
  • id 2

Doctor:

  • id 1

Professor:

  • id 2

Here is what I want to achieve:

Person:

  • id 1
  • id 2

Doctor:

  • id 1

Professor:

  • id 1
  • id 2

Here is what I get:

Person:

  • id 1
  • id 2
  • id 3 (same values as 1)

Doctor:

  • id 1

Professor:

  • id 2
  • id 3

I would appreciate any help, even if that is not possible maybe a hint on how to solve this using a different entity model approach or something else.

Thanks in advance guys!

Budenzauber
  • 113
  • 2
  • 10

1 Answers1

0

I think what you want to achieve is more of a role-model than inheritance. Is there a reason you don't assign roles to a person, like:

class Person {

  @ManyToMany
  private Set<Role> roles;

}

The flavour of @ManyToMany of course depends on the nature of Role - whether it's an Enum or a regular object itself.

Besides that: What's the reason you care for IDs yourself and don't let the database handle that, preferrably using a sequence generator? You should rather use foreign keys instead of copying object attributes and probably identify persons by their @NaturalId like e-mail address etc.

astriffe
  • 172
  • 14