OneToMany mapping with associative table with HIBERNATE - JPA

1

I need to map Hibernate from a 1:N relation to two tables, but there is an associative table that has the ids of the other two tables as columns.

Example:

The Servicos table can have many Itens and each item can only be part of a service.

And there is a servicos_itens table that contains the ID of the other two tables.

    
asked by anonymous 21.08.2018 / 18:59

1 answer

0

I think it would look something like this:

@Entity
class Servico {
    @OneToMany(mappedBy = "servico")
    private List<ServicoItem> listaServicoItem;
}

@Entity
class Item {
    @OneToOne(mappedBy = "item")
    private ServicoItem servicoItem;
}

@Entity
class ServicoItem {

    @JoinColumn(name = "servico_id")
    @ManyToOne
    private Servico servico;

    @JoinColumn(name = "item_id")
    @OneToOne
    private Item item;
}

And using:

List<ServicoItem> listaServicoItem = servico.getListaServicoItem;
Item item = listaServicoItem .get(0).getItem();
item.getServicoItem().getServico();
    
05.09.2018 / 22:34