【问题标题】:JPA - Override bean validation in joined-strategy inheritanceJPA - 在联合策略继承中覆盖 bean 验证
【发布时间】:2014-10-08 19:08:59
【问题描述】:

我有三个 JPA 实体:A、B 和 C。B 和 C 使用联合策略继承 A。是否可以覆盖子类中的 Bean Validation 约束?例如,我希望 B 在一个字段中具有 @NotNull 约束,而 C 在同一字段中具有 @Null 约束。

我想通过使用 Bean Validation 组来做到这一点,但是我不知道如何定义 B 必须用一个组验证,C 必须用另一个组验证。

说明问题的代码:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
...
public abstract class A {
    ...
    @Column(name="FIELD")
    private Integer field;
    ...
}

@Entity
public class B extends A {
    ...
    //@NotNull in field
    ...
}

@Entity
public class C extends A {
    ...
    //@Null in field
    ...
}

【问题讨论】:

    标签: jpa inheritance overriding bean-validation joined-subclass


    【解决方案1】:

    阅读关于条件 bean 验证的另一个问题,我想我已经找到了解决方案:Conditional Bean Validation

    它还没有经过测试,但我认为它可以工作。

    解决方案代码:

    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    ...
    public abstract class A {
        ...
        @Column(name="FIELD")
        private Integer field;
        ...
    }
    
    @Entity
    public class B extends A {
        ...
        @Transient
        @AssertTrue
        private boolean isValidClassA() {
            return (getField() != null); //Validates NotNull
        }
        ...
    }
    
    @Entity
    public class C extends A {
        ...
        @Transient
        @AssertTrue
        private boolean isValidClassA() {
            return (getField() == null); //Validates Null
        }
        ...
    }
    

    【讨论】:

    • 只是将属性字段移动到B和C会不会更容易?
    • 否,因为查询A实体时需要它。
    【解决方案2】:

    如果您在持久化或合并操作期间需要此验证,为什么不定义一个 pre prersist/update 回调?

    public class Base {
    
      protected String myData;
    }
    
    public class ConcreteA {
    
      @PrePersist
      @PreUpdate
      private void checkDataNotNull() {
        assert(mydata).isNotNull();
      }
    }
    
    public class ConcreteB {
    
      //myData may be null, so dont do any check
    }
    

    如果为空,则保证不会将数据保存到 ConcreteA 的数据库中,并且会引发错误。 如果字段不为空,您不再需要手动检查该字段。

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 2012-04-17
      • 1970-01-01
      • 2011-01-17
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      相关资源
      最近更新 更多