我在网上搜索,尝试了很多方法,但在删除过程中仍然遇到问题。请给我任何指示,因为我想了解我做错了什么。
我有几个实体,但简而言之:
public class PetOwner extends User {
private String address;
private String telefon;
@OneToMany(cascade={CascadeType.REMOVE})
private List<Appointment> appointments;
}
public class Appointment {
@Id
@GeneratedValue
private long id;
@ManyToOne(cascade={CascadeType.PERSIST})
@JoinColumn(name = "owner_id")
private PetOwner petOwner;
}
当我尝试使用此方法(JpaRepository)删除约会时
@Transactional
public void delete(Appointment appointment){
appointmentRepository.delete(appointment);
}
Spring 抛出异常:
MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
唯一的方法是在 Appointment.class 中设置
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name = "owner_id")
private PetOwner petOwner;
但随后除了 session 还删除了 PetOwner。请指导如何处理。
最佳答案
如果不参与关于创建层次结构以反射(reflect)属性(而非自然)的争论,您可以在此处使用两种方法。
首先,您可以更好地书写您的人际关系。我不知道您选择的 JPA 实现是什么,但有时它们会弄乱表格,从而创建不必要的链接表格。所以,安全总比后悔好:
在 PetOwner 上,使用:
@OneToMany(cascade={CascadeType.REMOVE}, mappedBy="petOwner")
private List<Appointment> appointments;
第二种方法是明确表示您的所有者在移除之前没有预约,因此:
@Transactional
public void delete(Appointment appointment){
appointment.getPetOwner().getAppointments().remove(appointment);
appointmentRepository.delete(appointment);
}
这真的很糟糕,因为当所有者有很多约会时,您可能会遇到巨大的性能问题。
关于java - JPA - 删除时出现 ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527127/