Use the same entity in Hibernate to write to two tables


I am using Hibernate to persist in the database, and in a given case, for every update that a given Consultor ed entity has, it should update in the main table called TB_Consultor and insert a new line in the TB_ConsultorHistorico table.

The structure of the TB_Consultor and TB_ConsultorHistorico tables 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? Being that in one there will be insertions and updates, and in the other, only insertions.

asked by anonymous 17.01.2014 / 18:45

1 answer


Inheritance with mapping via annotations

This is a very common question and most of the time it is indicated to use an embroidery based on inheritance. For example this answer gives us the basis for the following example:

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

public class Consultor extends ConsultorBase { ... }

public class ConsultorHistorico extends ConsultorBase { ... }

Mapping via XML

In other answers ( this and this ) suggests you use a separate XML file to map the entity. That way you do not need a superclass .

Mapping example:

<class name="Consultor" table="TB_Consultor"

<class name="Consultor" table="TB_ConsultorHistorico"

So, depending on the entity type you need, you call the appropriate session methods, such as the save :"Consultor", consultor);

Or:"ConsultorHistorico", Historico);

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

This response was based (but well adapted) from the SO .

17.01.2014 / 19:03