hibernate 如何在JPA中对至少一个非空字段强制验证

rpppsulh  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(144)

如何在JPA中强制验证至少一个非空字段。所有字段都可以为空,但至少应存在其中一个字段才能持久化。如何在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;
}
5uzkadbs

5uzkadbs1#

由于您使用Hibernate,因此可以使用org.hibernate.annotations.Check

@Entity
@Table(name = "social")
@Check(name="ONE_OFF_CONSTRAINT", 
       constraints = "(website IS NOT NULL) OR (facebook IS NOT NULL) OR (instagram IS NOT NULL)")
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;
}

相关问题