An entity that is inherited persists

1

I have a Person entity that is inherited from another Administrator entity. In the database I already have data in the Person entity and I want to associate a Person Administrator . How can I do this? I'm using hibernate , and using a class Dao that inherits JpaRepository

Class: Person

@Entity
@Getter
@Setter
@Inheritance(strategy = InheritanceType.JOINED)
public class Pessoa extends PersistableEntity<Long> { // Essa herança tem o Id, e os equals&hashCode

    private static final long serialVersionUID = 1L;

    private String nome;

Class: Administrator

@Entity
@Getter
@Setter
public class Administrador extends Pessoa {

    private static final long serialVersionUID = 1L;
    
asked by anonymous 02.04.2014 / 20:00

1 answer

2

Possible Solution

The question code would work with some adjustments to the notes. You could consider as if there were already data from the Administrador entity. If you retrieve a Administrador that does not have a record in its table, but is a Pessoa valid, Hibernate will probably generate a LEFT OUTER JOIN and retrieve existing data by ignoring the others. Then a update would include the data in the subclass table.

Note that this is an assumption. There may be details that will hinder this approach.

Problems

On the other hand, although it may make sense in the context of your application to be Administrador to be a Pessoa , this modeling causes problems for implementation. In fact, should Pessoa not be a Administrador ?

In any case, the inheritance as implemented in Hibernate is not so flexible as to reflect any hierarchy we create in classes. On the contrary, the 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 such as table per subclass only allow you to deal with a limited set of subclasses and not directly with superclasses.

It makes sense to use inheritance in Hibernate when a superclass has several possible subclasses, not just one. In this case, it is necessary to annotate the superclass with @DiscriminatorColumn to inform Hibernate of a column that defines what kind of subclass each record should represent.

Ideal Solution

In its context, my indication would be not to use inheritance, but a 1:1 relationship (one-to-one) between Pessoa and Administrador . More specifically, the Administrador class could have an attribute of type Pessoa . I imagine that the Administrador table already has a Foreign Key for Pessoa , does not it?

I know it may sound a bit strange, but it makes sense if you think in terms of:

  • Do not change the existing code in class Pessoa
  • Avoid unnecessary complexity in mapping with Hibernate
  • Do not impact features that use the Pessoa class, but have no dependency on the Administrador
  • It's simply simpler
02.04.2014 / 21:05