Possible Solution
The question code would work with some adjustments to the annotations. You might consider as if there were already entity data Administrador
. If you recover one Administrador
which does not have a record in the respective table, but is a Pessoa
valid, Hibernate will probably generate a LEFT OUTER JOIN
and recover existing data by ignoring others. So, a update
would include the data in the subclass table.
Note that this is an assumption. There may be details that prevent this approach.
Problems
On the other hand, although a Administrador
be a Pessoa
, this modeling brings problems to the implementation. Indeed, will the Pessoa
shouldn’t be a Administrador
?
In any case, the heritage as implemented in Hibernate is not so flexible as to reflect any hierarchy we create in classes. On the contrary, methods are very limited.
One of the most common examples is the question of polymorphism. For example, Hibernate even allows some kind of polymorphism, but in general, common inheritance strategies like table per subclass only allow you to handle a limited set of subclasses and not directly with the superclasses.
It makes sense to use Hibernate inheritance when a superclass has several possible subclasses and not just one. In this case, it is necessary to note the superclass with @DiscriminatorColumn
to inform Hibernate of a column that defines what kind of subclass each record should represent.
Ideal Solution
In your context, my indication would be not to use inheritance, but a relationship 1:1
(one-to-one) between Pessoa
and Administrador
. More specifically, the class Administrador
could have an attribute like Pessoa
. I imagine the table Administrador
already have a Foreign Key for Pessoa
, is not?
I know it might sound a little strange, but it makes sense if you think in terms of:
- Do not change existing code in class
Pessoa
- Avoid unnecessary complexity in mapping with Hibernate
- Do not impact functionalities that use the class
Pessoa
, but who has no dependency on the class Administrador
- It’s simply simpler
Really, friend makes sense that your answer much easier to make this relationship 1 to 1
– Maique