Relation N x N in Java objects

Asked

Viewed 196 times

1

I have an item table

(item_id (pk), descrição, ...),

A supplier table

(fornecedor_id (pk), nome, ...) 

and for being an Nxn relation I have an item_vendor intermediate table

(item_id (fk), fornecedor_id (fk), codigo, ...).

How do I create these 3 objects in Java (corresponding to each table), taking into account this relationship?

  • Is using Hibernate?

  • These annotations are provided as?

  • I am not using JPA. What is the alternative solution?

1 answer

0

I’ll share a solution with you.

You will only need to get a few details such as field names to do the get and set and hashcode and equals methods of the 4 classes

Item class

@Entity
@Table(name = "item")
public class Item {

    @Id
    @Column(name = "item_id", length = 20, precision = 0)
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long            id;

    @Column(name = "descricao")
    private String          descricao;

    //implementar os metodos corretamente hashCode equals, recomendavel

}

Supplier class

@Entity
@Table(name = "forncedor")
public class Fornecedor {

    @Id
    @Column(name = "forncedor_id", length = 20, precision = 0)
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long            id;

    @Column(name = "nome")
    private String          nome;

    //implementar os metodos corretamente hashCode equals, recomendavel

}

Relation class, the relation fields must be equal and more Must be equal to the DDL of the table

@Table(name = "item_fornecedor")
@IdClass(ItemFornecedorPk.class)
public class ItemFornecedor {

    private ItemFornecedorPk    pk;

    @Id
    @ManyToOne
    @JoinColumn(name = "item_id_pk", referencedColumnName = "id")
    private Item        item;

    @Id
    @ManyToOne
    @JoinColumn(name = "forncedor_id_pk", referencedColumnName = "id")
    private Fornecedor          fornecedor;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "campoSoDaRelacao")
    private Date            campoSoDaRelacao;

    //implementar os metodos corretamente hashCode equals, obrigatório

}

Class of the relationship key

@Embeddable
public class ItemFornecedorPk {


    @Id
    @ManyToOne
    @JoinColumn(name = "forncedor_id_pk", referencedColumnName = "forncedor_id", insertable = false, updatable = false)
    private Fornecedor      fornecedor;

    @Id
    @ManyToOne
    @JoinColumn(name = "item_id_pk", referencedColumnName = "item_id", insertable = false, updatable = false)
    private Item        item;

    //implementar os metodos corretamente hashCode equals, obrigatório
}

Now it is put to the Factory or pesistyUnit read and it already works. da make the lists also in the father of each, but ai only if you need.

Browser other questions tagged

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