How to reference a data already existing in the table with Hibernate

Asked

Viewed 71 times

0

I’m creating an api using Java with Springboot, and Ibernate. The idea is to save guests in the database, and these guests have a group, I don’t really understand the notes, but Mapeei with @Manytoone

@Entity
@Table(name = "con_convidado")
public class Convidado {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Length(max = 20)
    private String nome;


    @Enumerated(EnumType.STRING)
    private Gender genero;

    @ManyToOne(cascade = CascadeType.ALL)
    private Grupo grupo;


    @Enumerated(EnumType.STRING)
    private Age faixaEtaria;

    public Convidado() {

    }

Everything is working normally, but when I enter guests with the same group, in the database it creates a new line, and gets repeated information.

Group Class

@Entity
public class Grupo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String nome;

How to reuse what is already on the table, or improve the relationship between them.

  • maybe this post will help you https://answall.com/questions/234755/diferen%C3%A7as-onetomany-manytomany-manytoone-onetoone, but I think the Join column is missing.

  • You are sending the group with the completed existing id?

  • No, I’m sending it back in the requisition form, but I had seen somewhere that the data was not repeated

1 answer

0

If your relationship is just one Convidado X in a Grupo Y and a Group can contain several different Guests, so their relationship is:

In his Entity Grupo is that it must contain:

@ManyToAOne(cascade = CascadeType.ALL)
    private Convidado convidados;
  • Actually, the guest can only be in one group. Example: Guest : Bruno, Group : Familia, he can’t be in any other, so I put @Manytoone

  • So a Guest can only be in one correct group ? And a Group can have multiple guests ? So the relationship would be: @Manytoone in your Guest entity does not think ?

Browser other questions tagged

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