【问题标题】:Javax Constraints: if field 'Type' is XXX then apply @NotNull annotationJavax 约束:如果字段 \'Type\' 为 XXX,则应用 @NotNull 注释
【发布时间】:2022-08-15 17:55:51
【问题描述】:

我有一个带有 Postgres 的 Spring Boot 应用程序,它具有以下实体:

 @Entity
 @Table(name = \"message\")
 public class Message {

  public enum MessageType {
    TEXT,
    LOCATION,
    IMAGE,
    REPLY,
    LIST,
    BUTTON
  }

  @Id
  @GeneratedValue(generator = \"uuid\")
  @GenericGenerator(name = \"uuid\", strategy = \"uuid2\")
  private String id;

  @Column(nullable = false)
  private MessageType type;

  private String text;

  @Embedded
  private LocationRequest location;

  @Embedded
  private ImageRequest image;

  @Embedded
  private ContextRequest reply;

我需要做的是根据 MessageType 的值应用一些给定的约束。 例如,如果type 等于\"LOCATION\",那么我想确保 LocationRequest 的所有字段都是必需的(即不为空) 同样,如果类型是 Image,我希望 ImageRequest 的每个字段都是必需的。

这可以通过 Javax 约束来实现吗? 如果没有,是否有其他方法可以实现它,也许使用 Hibernate?

由于我的同事可能会使用 INSERT 直接向数据库添加记录,因此我需要为表而不是为我的应用程序生成这些约束(我正在使用 Hibernate 模式自动生成功能,ddl-auto=true)。

    标签: java postgresql spring-boot hibernate


    【解决方案1】:

    您可以使用检查约束来做到这一点,尽管它有点麻烦。像这样的东西:

    @Entity
    @Table(name = "message")
    @org.hibernate.annotations.Check("case type when 'LOCATION' then location_col1 is not null and locatoin_col2 is not null when 'IMAGE' then image_col1 is not null else true end")
    public class Message {
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 2018-12-17
      • 2013-01-15
      • 2011-11-21
      • 2017-10-15
      • 2013-11-17
      相关资源
      最近更新 更多