我有两个实体,相关如下
@Entity
@Table(name = "APPOINTMENT")
public class Appointment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long codeAp;
@ManyToOne(fetch = FetchType.EAGER)
, @OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "codeP")
private Patient patient;
//attributes
//getters and setters
//constructors
@Entity
@Table(name = "PATIENT")
public class Patient {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long codeP;
//attributes
//getters and setters
//constructors
我正在使用 JpaRepository 删除方法。 数据库中的表 PATIENT 和 APPOINTMENT 之间存在约束, 当我删除 Patient 时,我想删除孤儿。 我添加了@OnDelete hibernate 注释,但它对我不起作用! 你能告诉我为什么吗? 我想保持这种单向关系,你能帮我吗?
最佳答案
如果您只想继续使用关联作为单向关联,您可以在字段中定义延迟加载的反面,而无需为其公开 getter 和 setter:
@Entity
public class Patient {
@OneToMany(mappedBy = "patient", orphanRemoval = true)
private Collection<Appointment> appointments;
}
通过这种方式,orphanRemoval
逻辑从患者应用到他们的约会,作为奖励,您可以在 HQL 查询中从患者导航到约会。
注意 mappedBy
属性,它告诉预约负责关联管理,因此您可以通过将患者设置为 中定义的多对一关系来继续将预约与患者相关联约会
。
关于java - 删除父 manyToOne 注释时删除孤儿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43695185/