Hibernate - 在 one-to-many 关系中,child 在更新时丢失对 parent 的引用

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

如题,执行更新操作时,前面的child失去了对parent的引用。

Parent边

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

Children边

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

    @ManyToOne
    private Individual individual;

补丁操作

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

更新时,之前的 属性 丢失了对 child 的引用。我怎样才能避免这种情况?

通常使用 mappedBy 作为 @OneToMany 的参数而不是 @JoinColumn 来建立双向关系。

能不能试试改一下

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

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

看看效果是否更好?

您的映射似乎有误。理想情况下,它们应该如下所示:

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

    @ManyToOne 
    @JoinColumn
    private Individual individual;

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

您需要保存ContactMediumIndividual会自动保存。这里 ContactMedium 具有对 Individual 的外键引用(这就是您的数据库 table 屏幕截图中描述的内容)。

我认为您必须在 @ManyToOne 中添加 @OneToMany(mappedBy="individual" , cascade =CascadeType.PERSIST)@JoinColumn,如下所示:

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

@ManyToOne
@JoinColumn(name = "individual_id")
private Individual individual;

您应该先使用 ID 从数据库中检索实体,然后更新特定字段并将更新后的实体保存回来。