简体   繁体   中英

JPA - Override bean validation in joined-strategy inheritance

I have three JPA entities: A, B and C. B and C inherit A with joined strategy. Is it possible to override a Bean Validation constraint in the subclasses? For example, I would like B to have a @NotNull constraint in one field and C to have a @Null constraint in the same field.

I was thinking to do it by using Bean Validation groups, however I don't know how to define that B must be validated with one group and C with another group.

Code to illustrate the problem:

@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
    ...
}

I think I have come to a solution reading this other question about conditional bean validation: Conditional Bean Validation .

It is still not tested, but I think it could work.

Code of the solution:

@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
    }
    ...
}

If you need this validation during persist or merge operation, why dont you define a pre prersist/update callbacks?

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
}

You are guaranteed then that the data will not be save to the database for ConcreteA if it null, and an error will be raised. You no longer need to manually check the field if it is not null manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM