简体   繁体   中英

Java bean validation

I know this question has been asked before but unfortunately I can't get the answers to work ( How to validate field level constraint before class level constraint? ).

I have the following Pojo:

@ValidBalanceData(allowableBalanceDifference = 0.01)
public class Mutation {

    @NotNull() private BigDecimal balanceBefore;

    @NotNull() private BigDecimal balanceAfter;

    @NotNull() private BigDecimal amount;

    ....
}

I have implemented the ValidBalanceData annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BalanceDataConstraintChecker.class)
public @interface ValidBalanceData {
    String message() default "{nl.smith.balanceData.message}";

    double allowableBalanceDifference();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

I also implemented the validatedBy class. Unfortunately the ValidBalanceData constraint is validated before the NotNull constraints. Since the ValidBalanceData constraint assumes the balanceBefore, balanceAfter and amount values not to be null this results in a Nullpointer Exception. How do I solve this problem? Can somebody give me a working example (using @GroupSequence and fields)?

I found the answer:

@GroupSequence({ FieldChecks.class, Mutation.class })
@ValidBalanceData(allowableBalanceDifference = 0.01, groups =  Default.class)
public class Mutation {

private Integer id;

@NotNull(groups = FieldChecks.class)
private BigDecimal balanceBefore;

@NotNull(groups = FieldChecks.class)
private BigDecimal balanceAfter;

@NotNull(groups = FieldChecks.class)
private BigDecimal amount;

....

}

FieldChecks is a userdefined empty marker interface and javax.validation.groups.Default comes from the validation jar.

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