Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

operator precedence - Control validation annotations order?

A field has two validation annotations

@NotEmpty
@Length(min=3,max=100)
String firstName;

Observation

If that field is left empty, then the resulting violations vary in order:

  • sometimes the @NotEmpty is violated first
  • other times the @Length is violated first

Questions

How does Hibernate specify the order in which validations (annotations) are processed? Can this validation order be customized?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use JSR-303 validation groups.

If no groups are specified a constraint is part of the Default Bean Validation group (see: javax.validation.groups.Default).

Create an interface to be your "Extended" (or whatever you want to call it) group:

public interface Extended{}

Now create an interface that will have the javax.validation.GroupSequence annotation.

@GroupSequence({Default.class, Extended.class})
public interface MySequence {}

Set the validation groups on your constraints

@NotEmpty // If no group is specified it is part of the default group
@Length(min=3,max=100, groups = Extended.class)
String firstName;

Pass MySequence to your validator call.

validator.validate(object, MySequence.class);

As specified by your @GroupSequence the default constraints will be validated first and if no contraint violations are encountered it will move on to the extended group.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...