Onetomany mapping with HIBERNATE associative table - JPA

Asked

Viewed 521 times

1

I need to do a hibernate mapping of a relationship 1:N in two tables, however there is an associative table that has as columns the ids of the other two tables.

Example:

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

And there’s a table servicos_itens containing the ID of the other two tables.

  • These foreign keys in the associative table are also ids of this table (i.e., they are composite key) or it has, in addition to these 2 fields, a specific field for id?

1 answer

0

I think it would be 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();

Browser other questions tagged

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