我有一个实体,其他实体有三个外键:
public class MyClass {
// ...
@OneToOne(cascade = CascadeType.ALL, optional = false)
@JoinColumn(name = "customer_id")
public Customer getCustomer() {
return customer;
}
@OneToOne(cascade = CascadeType.ALL, optional = true)
@JoinColumn(name = "creditDossier_id")
public CreditDossier getCreditDossier() {
return creditDossier;
}
@OneToOne(cascade = CascadeType.ALL, optional = true)
@JoinColumn(name = "insuranceDossier_id")
public InsuranceDossier getInsuranceDossier() {
return insuranceDossier;
}
// ...
}
如何添加限制,以保证*档案中至少有一个不为空。
答案 0 :(得分:4)
您应该在实体类中编写一个带注释@PrePersist
的方法,它会在持久化之前检查您的限制。
@PrePersist
public void checkValidation(){
if(isValid()){
// send for persist.
}
else{
//throws Exception.
}
}
private boolean isValid(){
return customer!=null || creditDossier!=null || insuranceDossier!=null;
}