Doing JSR-303 validation in logical order

橙三吉。 提交于 2019-12-06 08:09:37

According to Hibernate official document:

By default, constraints are evaluated in no particular order and this regardless of which groups they belong to. In some situations, however, it is useful to control the order of the constraints evaluation. In order to implement such an order one would define a new interface and annotate it with @GroupSequence defining the order in which the groups have to be validated.

At first, create two interface FirstOrder.class and SecondOrder.class and then define a group sequence inside OrderedChecks.java using @GroupSequence annotation.

public interface FirstOrder {
}

public interface SecondOrder {
}

@GroupSequence({FirstOrder.class, SecondOrder.class})
public interface OrderedChecks {
}

Finally, add groups in your bean constraints annotations.

@Column(nullable = false, name = "name")
@NotEmpty(groups = {FirstOrder.class, Envelope.Insert.class, Envelope.Update.class})
@Size(min = 3, max = 32, groups=SecondOrder.class)
private String name;

The following example is taken from the JSR-303 docs

public class Address {
    @NotEmpty(groups = Minimal.class)
    @Size(max=50, groups=FirstStep.class)
    private String street1;

    @NotEmpty(groups=SecondStep.class)
    private String city;

    @NotEmpty(groups = {Minimal.class, SecondStep.class})
    private String zipCode;
    ...

    public interface FirstStep {}

    public interface SecondStep {}

    @GroupSequence({Firststep.class, SecondStep.class})
    public interface Total {}
}

and calling the validator like this

validator.validate(address, Minimal.class, Total.class);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!