Use the same entity in Hibernate to write to two tables

Asked

Viewed 1,567 times

14

I am using Hibernate to make the persistence in the database, and in a given case, for each update that a certain entity Consultor has, it must update in the main table called TB_Consultorand insert a new row in the table TB_ConsultorHistorico.

The structure of the tables TB_Consultor and TB_ConsultorHistorico are identical and thus what I’m avoiding is having to map an entity Consultor and another ConsultorHistorico that will be identical, and do everything with one entity.

Is it possible to map with Hibernate for the same entity to write to two tables in the database? In one there will be insertions and updates, and in the other, only insertions.

1 answer

4


Inheritance with mapping via annotations

This is a very common question and it is most often indicated to use a heritage-based border. For example this answer gives us basis for the following example:

@MappedSuperclass
public class ConsultorBase { /* código da classe vai aqui */ }

@Entity
@Table(name="TB_Consultor")
public class Consultor extends ConsultorBase { ... }

@Entity
@Table(name="TB_ConsultorHistorico")
public class ConsultorHistorico extends ConsultorBase { ... }

Mapping via XML

In other answers (this and this) it is suggested to use a separate XML file to map the entity. This way you do not need a superclass.

Example of mapping:

<class name="Consultor" table="TB_Consultor"
        entity-name="Consultor">
    ...
</class>

<class name="Consultor" table="TB_ConsultorHistorico"
        entity-name="ConsultorHistorico">
    ...
</class>

So depending on the type of entity you need, you call the appropriate session methods, such as the method save:

session.save("Consultor", consultor);

Or:

session.save("ConsultorHistorico", Historico);

To official documentation, that inspired the above example, says that to do the disambiguation, we need to use the entity name, both in XML and in the parameter.


This response was based (but well adapted) on the original ONLY.

  • 1

    Thank you, I had to make some adaptations with @Attributeoverride because the tables were not 100% equal, because in one the ID was the primary key, and in the other not, but in the end it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.