Search code examples
hibernatejpaspring-data-jpa

How to enforce validation on atleast one field being non null in JPA


How to enforce validation on atleast one field being non null in JPA. All fields are nullable but atleast one of them should be present to be persisted. How to enforce this validation in JPA.

@Entity
@Table(name = "social")
public class Social {

    @Column(name = "website", nullable = true)
    private String website;

    @Column(name = "facebook", nullable = true)
    private String facebook;

    @Column(name = "instagram", nullable = true)
    private String instagram;
}

Solution

  • You have 2 options:

    1. If you let Hibernate generate your table model, you can use the @Check annotation described by Dirk in a previous comment. Hibernate then adds a constraint to the table, and your database checks it when you insert or update a record. But please be aware that Hibernate doesn't perform any check itself. You totally rely on the constraint being added to your table model (which only happens if Hibernate generates it).
    2. You can add a method to your entity class, annotate it with @PrePersist and @PreUpdate and implement the validation yourself. This would be my recommended approach (with or without an additional database constraint).

    Here's a quick example of option 2:

    @Entity
    @Table(name = "social")
    public class Social {
    
        @Column(name = "website", nullable = true)
        private String website;
    
        @Column(name = "facebook", nullable = true)
        private String facebook;
    
        @Column(name = "instagram", nullable = true)
        private String instagram;
    
        @PrePersist
        @PreUpdate
        public void notNullCheck() {
            if (website == null && facebook == null && instagram == null) {
                throw new RuntimeException("Website, facebook and instagram are null. At least one of them has to be set.");
            }
        }
    }