Search code examples
javahibernatespring-data-jpahibernate-mappingcascade

Hibernate - In a one-to-many relationship, a child loses references to the parent when updating


As in the title, when performing the update operation, the previous child loses the reference to the parent.

Parent side

@OneToMany(cascade =CascadeType.ALL)
@JoinColumn(name = "individual_id")
private List<ContactMedium> contactMedium;

Children side

@Entity
@Table(name = "contactMedium")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ContactMedium 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id ;

    @ManyToOne
    private Individual individual;

Patch operation

 public Individual patch(Individual individual, Long id) {
        Individual objectToSave = individual;
        objectToSave.setId(id);
        return individualRepository.save(objectToSave);
    }

When updating, the previous property loses references to the child. How can I prevent this?

enter image description here


Solution

  • Your mappings seems wrong. Ideally they should be as below:

    @Entity
    @Table(name = "contactMedium")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class ContactMedium 
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id ;
    
        @ManyToOne 
        @JoinColumn
        private Individual individual;
    

    and

    @OneToMany(mappedBy = "individual", cascade = CascadeType.ALL)
    private List<ContactMedium> contactMedium;
    

    You need to save the ContactMedium and Individual will automatically be saved. Here ContactMedium has the foreign key reference to Individual (and that is what is depicted in your database table screenshot).