1

Is it possible in hibernate to model a use case in which you have two fields and either of them could be null but at least one of them must not be null? Below is the code I have at the moment but I don't like the fact that I have to set both of them to @Column(nullable = true). In my case I want either the personal email address or the work address. Is there a good way to support this? Or is an alternative approach needed?

public class ApplicantDetails {

    //...

    @OneToOne(optional = false)
    private ContactDetails contactDetails;

    //...
}

public class ContactDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    /*Need at least one email address but it doesn't matter which one.*/
    @Column(nullable = true, unique = true)
    private String personalEmail;

    @Column(nullable = true, unique = true)
    private String workEmail;

    //...

}
james_s_tayler
  • 1,823
  • 1
  • 15
  • 20

1 Answers1

1

I would recommend that you anyway define a CHECK constraint in the database if your database supports some form of it:

CHECK (PERSONAL_EMAIL IS NOT NULL OR WORK_EMAIL IS NOT NULL)

Regarding the middle layer, you can simply write your own validators in services that store/update ContactDetails and raise the corresponding exceptions if attempts to store/update inconsistent state are made, or you can use a validation framework like Hibernate validator.

A quick workaround could also be to utilise entity lifecycle callback methods:

@PrePersist
@PreUpdate
private void validate() {
  if (personalEmail == null && workEmail == null) {
    throw new ValidationException();
  }
} 
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110