Hibernate + Inheritance

4

I'm trying for some time a solution to my problem. I have researched a lot but nothing explains me clearly what I need.

So I created an example application and I'm making it available from this link: Appliance

To run this application, simply use the NetBeans IDE and create a MySql DB with the following name: "testHeranca".

My question is:

I have two entities, Participant and Issuer. The Issuer class extends the participating class. For example:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "participante")
public class Participante implements Serializable{

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;
    @Column(name = "nome", nullable = false, length = 100)
    private String nome;
    @Column(name = "documento", nullable = false, length = 100)
    private String documento;
    ...
}



@Entity
@Table(name = "emitente")
@PrimaryKeyJoinColumn(name = "id")
public class Emitente extends Participante{

    @Column(name = "cargo", nullable = false, length = 100)
    private String cargo;
    ...
}

Suppose I have a participant already registered in my database, if I want to register a new issuer from this already existing participant, how should I proceed? Does Hibernate do this for me? With the test I passed in the example this does not happen.

    
asked by anonymous 05.08.2014 / 22:25

1 answer

3

Although you do not know all the details of Hibernate and other JPA implementations, as each has its own particularities, I do not think it's possible to have part of an inheritance relationship included.

Thinking that JPA works with a limited kind of polymorphism, this would be like changing the type of the object.

In this particular situation, a viable alternative would be to change the inheritance relationship type to aggregation, that is, where Emitente has an attribute of type Participante . That way the tables do not have to be changed and you can include separate entities at any time.

Other alternatives exist, as already mentioned in Anthony Accioly's comment:

  • Include the issuer via JDBC or Native Query and then read via JPA
  • Remove the participant and re-include them as an issuer
  • 05.08.2014 / 23:59