jpa-delete-onetomany违反了外键约束

k10s72fa  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(403)

我有两个Map实体, AssignmentOpsEntity 以及 ConventionalOptionEntity . 我想移除一个 AssignmentOpsEntity 全部 conventionalOption . 所以我取消了所有的常规选项 AssignmentOpsEntity ,然后我从数据库中删除了常规选项,最后我删除了对象 AssignmentOpsEntity . 但我有下面的错误。
错误:对表“assignmentoptentity”的更新或删除违反了对表“conventionaloptionentity”d的外键约束“fkll31qdog9ye067ybhltjey6u7”é尾 : 键(assignmentopsid)=(8bf4a6b3-c09e-4da1-a88d-d49d9f7b63f6)仍从表“常规选项”中引用。

@Entity
public class AssignmentOpsEntity {

  @OneToMany(mappedBy = "assignmentOps", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  private Set<ConventionalOptionEntity> conventionalOption;

  public void removeConventionalOption(Set<ConventionalOptionEntity> conventionalOption) {
    this.conventionalOption.removeAll(conventionalOption);
    conventionalOption.forEach(item -> item.assignmentOps(null));
  }

}

@Entity
public class ConventionalOptionEntity {

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    private AssignmentOpsEntity assignmentOps;

}

public void on(OpsDetachedFromAgreementEvent event) {
    Optional<AssignmentOpsEntity> assignmentOpsEntityOptional = assignmentOpsRepository.findById(event.assignmentOpsId);
    if (assignmentOpsEntityOptional.isPresent()) {
        AssignmentOpsEntity assignmentOpsEntity = assignmentOpsEntityOptional.get();
        assignmentOpsEntity.removeConventionalOption(assignmentOpsEntity.getConventionalOption());
        conventionalOptionRepository.deleteAll(assignmentOpsEntity.getConventionalOption());
        assignmentOpsRepository.delete(assignmentOpsEntity);
    }
}
txu3uszq

txu3uszq1#

@OneToMany(mappedBy = "assignmentOps", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<ConventionalOptionEntity> conventionalOption;
``` `CascadeType.ALL` 这里的意思是 `conventionalOption` 删除父实体时将删除实体
所以这里是你需要的代码

public void on(OpsDetachedFromAgreementEvent event) {
Optional assignmentOpsEntityOptional = assignmentOpsRepository.findById(event.assignmentOpsId);
if (assignmentOpsEntityOptional.isPresent()) {
assignmentOpsRepository.delete(assignmentOpsEntity);
}
}

相关问题