-1

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

Grafik Krystian
  • 179
  • 2
  • 13

4 Answers4

0

Often one use mappedBy as parameter to @OneToMany instead of @JoinColumn to make the relationship two-ways.

Can you please try to change

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

to

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

and see if that worked better?

Kaj Hejer
  • 955
  • 4
  • 18
0

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).

Jignesh M. Khatri
  • 1,407
  • 1
  • 14
  • 22
0

I think you must add the @OneToMany(mappedBy="individual" , cascade =CascadeType.PERSIST) and the @JoinColumn in the @ManyToOne as below:

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

@ManyToOne
@JoinColumn(name = "individual_id")
private Individual individual;
Med Elgarnaoui
  • 1,612
  • 1
  • 18
  • 35
0

You should retrieve the entity from the database using the ID first and then update the specific fields and persist the updated entity back.

Upesh M
  • 382
  • 1
  • 4
  • 9