Vasco Correia
Vasco Correia

Reputation: 75

Hibernate - Of three columns, at least one must be not-null

I have an entity that has three foreign key to other entities:

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;
    }

    // ...
}

How can I add a restriction that guarantees that at least one of the *Dossier is not null.

Upvotes: 4

Views: 462

Answers (1)

Masudul
Masudul

Reputation: 21971

You should write a method with annotating @PrePersist in your entity class, which will check the your restrictions before persist.

   @PrePersist
   public void checkValidation(){
       if(isValid()){
           // send for persist.
       }
       else{
           //throws Exception.  
       }         
   }

   private boolean isValid(){
        return customer!=null || creditDossier!=null || insuranceDossier!=null;
   }

Upvotes: 4

Related Questions