简体   繁体   中英

How to reference existing data in table with hibernate

I'm creating a api with Java, Spring Boot and Hibernate. The objective is save guests in a list.

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

There is the class Guest

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

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

    @Length(max = 20)
    private String name;


    @Enumerated(EnumType.STRING)
    private Gender gender;

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


    @Enumerated(EnumType.STRING)
    private Age ageRange;

    public Convidado() {

    }

And the class Group

@Entity
public class Grupo {

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

    private String nome;

I wish that when I inserted a new guest with an existing group, a new group with the same name would not be created.

You group is using id as primary key. If you want your new guest to be created in the existing group you need to set its id.

Something like that

var group = findGroupByName(name);
if (group == null) group = new Group(name);
guest2.setGroup(group);

Or you can just make group.name your PK by removing id and marking name with @Id annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM