-
Notifications
You must be signed in to change notification settings - Fork 566
/
usingvalidator.xml
1512 lines (1163 loc) · 56.1 KB
/
usingvalidator.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ JBoss, Home of Professional Open Source
~ Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
~ by the @authors tag. See the copyright.txt in the distribution for a
~ full listing of individual contributors.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~ http://www.apache.org/licenses/LICENSE-2.0
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../hv.ent">
%BOOK_ENTITIES;
]>
<chapter id="validator-usingvalidator">
<title>Validation step by step</title>
<para>In this chapter we will see in more detail how to use Hibernate
Validator to validate constraints for a given entity model. We will also
learn which default constraints the Bean Validation specification provides
and which additional constraints are only provided by Hibernate Validator.
Let's start with how to add constraints to an entity.</para>
<section id="validator-usingvalidator-annotate">
<title>Defining constraints</title>
<para>Constraints in Bean Validation are expressed via Java annotations.
In this section we show how to annotate an object model with these
annotations. We have to differentiate between three different type of
constraint annotations - field-, property-, and class-level
annotations.</para>
<note>
<para>Not all constraints can be placed on all of these levels. In fact,
none of the default constraints defined by Bean Validation can be placed
at class level. The <classname>java.lang.annotation.Target</classname>
annotation in the constraint annotation itself determines on which
elements a constraint can be placed. See <xref
linkend="validator-customconstraints" /> for more information.</para>
</note>
<section>
<title>Field-level constraints</title>
<para>Constraints can be expressed by annotating a field of a class.
<xref linkend="example-field-level" /> shows a field level configuration
example:</para>
<example id="example-field-level">
<title>Field level constraint</title>
<programlisting language="JAVA" role="JAVA">package com.mycompany;
import javax.validation.constraints.NotNull;
public class Car {
@NotNull
private String manufacturer;
@AssertTrue
private boolean isRegistered;
public Car(String manufacturer, boolean isRegistered) {
super();
this.manufacturer = manufacturer;
this.isRegistered = isRegistered;
}
}</programlisting>
</example>
<para>When using field level constraints field access strategy is used
to access the value to be validated. This means the bean validation
provider directly accesses the instance variable and does not invoke the
property accessor method also if such a method exists.</para>
<note>
<para>The access type (private, protected or public) does not
matter.</para>
</note>
<note>
<para>Static fields and properties cannot be validated.</para>
</note>
<tip>
<para>When validating byte code enhanced objects property level
constraints should be used, because the byte code enhancing library
won't be able to determine a field access via reflection.</para>
</tip>
</section>
<section>
<title>Property-level constraints</title>
<para>If your model class adheres to the <ulink type=""
url="http://java.sun.com/javase/technologies/desktop/javabeans/index.jsp">JavaBeans</ulink>
standard, it is also possible to annotate the properties of a bean class
instead of its fields. <xref linkend="example-property-level" /> uses
the same entity as in <xref linkend="example-field-level" />, however,
property level constraints are used.<note>
<para>The property's getter method has to be annotated, not its
setter.</para>
</note></para>
<example id="example-property-level">
<title>Property level constraint</title>
<programlisting language="JAVA" role="JAVA">package com.mycompany;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;
public class Car {
private String manufacturer;
private boolean isRegistered;
public Car(String manufacturer, boolean isRegistered) {
super();
this.manufacturer = manufacturer;
this.isRegistered = isRegistered;
}
@NotNull
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
@AssertTrue
public boolean isRegistered() {
return isRegistered;
}
public void setRegistered(boolean isRegistered) {
this.isRegistered = isRegistered;
}
}</programlisting>
</example>
<para>When using property level constraints property access strategy is
used to access the value to be validated. This means the bean validation
provider accesses the state via the property accessor method. One
advantage of annotating properties instead of fields is that the
constraints become part of the constrained type's API that way and users
are aware of the existing constraints without having to examine the
type's implementation.</para>
<tip>
<para>It is recommended to stick either to field
<emphasis>or</emphasis> property annotations within one class. It is
not recommended to annotate a field <emphasis>and</emphasis> the
accompanying getter method as this would cause the field to be
validated twice.</para>
</tip>
</section>
<section>
<title id="validator-usingvalidator-classlevel">Class-level
constraints</title>
<para>Last but not least, a constraint can also be placed on class
level. When a constraint annotation is placed on this level the class
instance itself passed to the
<classname>ConstraintValidator</classname>. Class level constraints are
useful if it is necessary to inspect more than a single property of the
class to validate it or if a correlation between different state
variables has to be evaluated. In <xref linkend="example-class-level" />
we add the property <property>passengers</property> to the class
<classname>Car</classname>. We also add the constraint
<classname>PassengerCount</classname> on the class level. We will later
see how we can actually create this custom constraint (see <xref
linkend="validator-customconstraints" />). For now it is enough to know
that <classname>PassengerCount</classname> will ensure that there cannot
be more passengers in a car than there are seats.</para>
<example id="example-class-level">
<title>Class level constraint</title>
<programlisting language="JAVA" role="JAVA">package com.mycompany;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@PassengerCount
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
private List<Person> passengers;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}</programlisting>
</example>
</section>
<section>
<title>Constraint inheritance</title>
<para>When validating an object that implements an interface or extends
another class, all constraint annotations on the implemented interface
and parent class apply in the same manner as the constraints specified
on the validated object itself. To make things clearer let's have a look
at the following example:</para>
<example>
<title>Constraint inheritance using RentalCar</title>
<programlisting language="JAVA" role="JAVA">package com.mycompany;
import javax.validation.constraints.NotNull;
public class RentalCar extends Car {
private String rentalStation;
public RentalCar(String manufacturer, String rentalStation) {
super(manufacturer);
this.rentalStation = rentalStation;
}
@NotNull
public String getRentalStation() {
return rentalStation;
}
public void setRentalStation(String rentalStation) {
this.rentalStation = rentalStation;
}
}</programlisting>
</example>
<para>Our well-known class <classname>Car</classname> is now extended by
<classname>RentalCar</classname> with the additional property
<property>rentalStation</property>. If an instance of
<classname>RentalCar</classname> is validated, not only the
<classname>@NotNull</classname> constraint on
<property>rentalStation</property> is validated, but also the constraint
on <property>manufacturer</property> from the parent class.</para>
<para>The same would hold true, if <classname>Car</classname> were an
interface implemented by <classname>RentalCar</classname>.</para>
<para>Constraint annotations are aggregated if methods are overridden.
If <classname>RentalCar</classname> would override the
<methodname>getManufacturer()</methodname> method from
<classname>Car</classname> any constraints annotated at the overriding
method would be evaluated in addition to the
<classname>@NotNull</classname> constraint from the super-class.</para>
</section>
<section>
<title>Object graphs</title>
<para>The Bean Validation API does not only allow to validate single
class instances but also complete object graphs. To do so, just annotate
a field or property representing a reference to another object with
<classname>@Valid</classname>. If the parent object is validated, all
referenced objects annotated with <classname>@Valid</classname> will be
validated as well (as will be their children etc.). See <xref
linkend="example-car-with-driver" />.</para>
<example>
<title>Class Person</title>
<programlisting language="JAVA" role="JAVA">package com.mycompany;
import javax.validation.constraints.NotNull;
public class Person {
@NotNull
private String name;
public Person(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}</programlisting>
</example>
<example id="example-car-with-driver">
<title>Adding a driver to the car</title>
<programlisting language="JAVA" role="JAVA">package com.mycompany;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
public class Car {
@NotNull
@Valid
private Person driver;
public Car(Person driver) {
this.driver = driver;
}
//getters and setters ...
}</programlisting>
</example>
<para>If an instance of <classname>Car</classname> is validated, the
referenced <classname>Person</classname> object will be validated as
well, as the <property>driver</property> field is annotated with
<classname>@Valid</classname>. Therefore the validation of a
<classname>Car</classname> will fail if the <property>name</property>
field of the referenced <classname>Person</classname> instance is
<code>null</code>.</para>
<para>Object graph validation also works for collection-typed fields.
That means any attributes that</para>
<itemizedlist>
<listitem>
<para>are arrays</para>
</listitem>
<listitem>
<para>implement <classname>java.lang.Iterable</classname>
(especially <classname>Collection</classname>,
<classname>List</classname> and <classname>Set</classname>)</para>
</listitem>
<listitem>
<para>implement <classname>java.util.Map</classname></para>
</listitem>
</itemizedlist>
<para>can be annotated with <classname>@Valid</classname>, which will
cause each contained element to be validated, when the parent object is
validated.</para>
<example>
<title>Car with a list of passengers</title>
<programlisting language="JAVA" role="JAVA">package com.mycompany;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
public class Car {
@NotNull
@Valid
private List<Person> passengers = new ArrayList<Person>();
public Car(List<Person> passengers) {
this.passengers = passengers;
}
//getters and setters ...
}</programlisting>
</example>
<para>If a <classname>Car</classname> instance is validated, a
<classname>ConstraintValidation</classname> will be created, if any of
the <classname>Person</classname> objects contained in the
<property>passengers</property> list has a <code>null</code> name.<note>
<para><classname>null</classname> values are getting ignored when
validating object graphs.</para>
</note></para>
</section>
</section>
<section id="validator-usingvalidator-validate">
<title>Validating constraints</title>
<para>The <classname>Validator</classname> interface is the main entry
point to Bean Validation. In <xref linkend="section-validator-instance" />
we will first show how to obtain an <classname>Validator</classname>
instance. Afterwards we will learn how to use the different methods of the
<classname>Validator</classname> interface.</para>
<section id="section-obtaining-validator">
<title>Obtaining a <classname>Validator</classname> instance</title>
<para>The first step towards validating an entity instance is to get
hold of a <classname>Validator</classname> instance. The road to this
instance leads via the <classname>Validation</classname> class and a
<classname>ValidatorFactory</classname>. The easiest way is to use the
static
<methodname>Validation.buildDefaultValidatorFactory()</methodname>
method:</para>
<example>
<title>Validation.buildDefaultValidatorFactory()</title>
<programlisting language="JAVA" role="JAVA">ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();</programlisting>
</example>
<para>For other ways of obtaining a Validator instance see <xref
linkend="validator-bootstrapping" />. For now we just want to see how we
can use the <classname>Validator</classname> instance to validate entity
instances.</para>
</section>
<section>
<title>Validator methods</title>
<para>The <classname>Validator</classname> interface contains three
methods that can be used to either validate entire entities or just a
single properties of the entity.</para>
<para>All three methods return a
<classname>Set<ConstraintViolation></classname>. The set is empty,
if the validation succeeds. Otherwise a
<classname>ConstraintViolation</classname> instance is added for each
violated constraint.</para>
<para>All the validation methods have a var-args parameter which can be
used to specify, which validation groups shall be considered when
performing the validation. If the parameter is not specified the default
validation group
(<classname>javax.validation.groups.Default</classname>) will be used.
We will go into more detail on the topic of validation groups in <xref
linkend="validator-usingvalidator-validationgroups" /></para>
<section>
<title><methodname>validate</methodname></title>
<para>Use the <methodname>validate()</methodname> method to perform
validation of all constraints of a given entity instance (see <xref
linkend="example-validator-validate" /> ).</para>
<example id="example-validator-validate">
<title>Usage of
<methodname>Validator.validate()</methodname></title>
<programlisting language="JAVA" role="JAVA">ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Car car = new Car(null);
Set<ConstraintViolation<Car>> constraintViolations = validator.validate(car);
assertEquals(1, constraintViolations.size());
assertEquals("may not be null", constraintViolations.iterator().next().getMessage());</programlisting>
</example>
</section>
<section>
<title><methodname>validateProperty</methodname></title>
<para>With help of the <methodname>validateProperty()</methodname> a
single named property of a given object can be validated. The property
name is the JavaBeans property name.</para>
<example>
<title>Usage of
<methodname>Validator.validateProperty()</methodname></title>
<programlisting language="JAVA" role="JAVA">Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Car car = new Car(null);
Set<ConstraintViolation<Car>> constraintViolations = validator.validateProperty(car, "manufacturer");
assertEquals(1, constraintViolations.size());
assertEquals("may not be null", constraintViolations.iterator().next().getMessage());</programlisting>
</example>
<para><methodname>Validator.validateProperty</methodname> is for
example used in the integration of Bean Validation into JSF 2 (see
<xref linkend="section-presentation-layer" />).</para>
</section>
<section>
<title><methodname>validateValue</methodname></title>
<para>Using the <methodname>validateValue() </methodname>method you
can check, whether a single property of a given class can be validated
successfully, if the property had the specified value:</para>
<example>
<title>Usage of
<methodname>Validator.validateValue()</methodname></title>
<programlisting language="JAVA" role="JAVA">Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Car>> constraintViolations = validator.validateValue(Car.class, "manufacturer", null);
assertEquals(1, constraintViolations.size());
assertEquals("may not be null", constraintViolations.iterator().next().getMessage());</programlisting>
</example>
<note>
<para><classname>@Valid</classname> is not honored by
<methodname>validateProperty()</methodname> or
<methodname>validateValue()</methodname>.</para>
</note>
</section>
</section>
<section>
<title><classname>ConstraintViolation</classname> methods</title>
<para>Now it is time to have a closer look at what a
<classname>ConstraintViolation</classname>. Using the different methods
of <classname>ConstraintViolation</classname> a lot of useful
information about the cause of the validation failure can be determined.
<xref linkend="table-constraint-violation" /> gives an overview of these
methods:</para>
<table id="table-constraint-violation">
<title>The various <classname>ConstraintViolation</classname>
methods</title>
<tgroup cols="3">
<thead>
<row>
<entry>Method</entry>
<entry>Usage</entry>
<entry>Example (referring to <xref
linkend="example-validator-validate" />)</entry>
</row>
</thead>
<tbody>
<row>
<entry><methodname>getMessage()</methodname></entry>
<entry>The interpolated error message.</entry>
<entry>may not be null</entry>
</row>
<row>
<entry><methodname>getMessageTemplate()</methodname></entry>
<entry>The non-interpolated error message.</entry>
<entry>{javax.validation.constraints.NotNull.message}</entry>
</row>
<row>
<entry><methodname>getRootBean()</methodname></entry>
<entry>The root bean being validated.</entry>
<entry>car</entry>
</row>
<row>
<entry><methodname>getRootBeanClass()</methodname></entry>
<entry>The class of the root bean being validated.</entry>
<entry>Car.class</entry>
</row>
<row>
<entry><methodname>getLeafBean()</methodname></entry>
<entry>If a bean constraint, the bean instance the constraint is
applied on. If a property constraint, the bean instance hosting
the property the constraint is applied on.</entry>
<entry>car</entry>
</row>
<row>
<entry><methodname>getPropertyPath()</methodname></entry>
<entry>The property path to the value from root bean.</entry>
<entry></entry>
</row>
<row>
<entry><methodname>getInvalidValue()</methodname></entry>
<entry>The value failing to pass the constraint.</entry>
<entry>passengers</entry>
</row>
<row>
<entry><methodname>getConstraintDescriptor()</methodname></entry>
<entry>Constraint metadata reported to fail.</entry>
<entry></entry>
</row>
</tbody>
</tgroup>
</table>
</section>
<section id="section-message-interpolation">
<title>Message interpolation</title>
<para>As we will see in <xref linkend="validator-customconstraints" />
each constraint definition must define a default message descriptor.
This message can be overridden at declaration time using the
<methodname>message</methodname> attribute of the constraint. You can
see this in <xref linkend="example-driver" />. This message descriptors
get interpolated when a constraint validation fails using the configured
<classname>MessageInterpolator</classname>. The interpolator will try to
resolve any message parameters, meaning string literals enclosed in
braces. In order to resolve these parameters Hibernate Validator's
default <classname>MessageInterpolator</classname> first recursively
resolves parameters against a custom
<classname>ResourceBundle</classname> called
<filename>ValidationMessages.properties</filename> at the root of the
classpath (It is up to you to create this file). If no further
replacements are possible against the custom bundle the default
<classname>ResourceBundle</classname> under
<filename>/org/hibernate/validator/ValidationMessages.properties</filename>
gets evaluated. If a replacement occurs against the default bundle the
algorithm looks again at the custom bundle (and so on). Once no further
replacements against these two resource bundles are possible remaining
parameters are getting resolved against the attributes of the constraint
to be validated.</para>
<para>Since the braces { and } have special meaning in the messages they
need to be escaped if they are used literally. The following The
following rules apply:<itemizedlist>
<listitem>
<para>\{ is considered as the literal {</para>
</listitem>
<listitem>
<para>\} is considered as the literal }</para>
</listitem>
<listitem>
<para>\\ is considered as the literal \</para>
</listitem>
</itemizedlist></para>
<para>If the default message interpolator does not fit your requirements
it is possible to plug a custom
<classname>MessageInterpolator</classname> when the
<classname>ValidatorFactory</classname> gets created. This can be seen
in <xref linkend="validator-bootstrapping" />.</para>
</section>
</section>
<section id="validator-usingvalidator-validationgroups">
<title>Validating groups</title>
<para>Groups allow you to restrict the set of constraints applied during
validation. This makes for example wizard like validation possible where
in each step only a specified subset of constraints get validated. The
groups targeted are passed as var-args parameters to
<methodname>validate</methodname>,
<methodname>validateProperty</methodname> and
<methodname>validateValue</methodname>. Let's have a look at an extended
<classname>Car</classname> with <classname>Driver</classname> example.
First we have the class <classname>Person</classname> (<xref
linkend="example-person" />) which has a <classname>@NotNull
</classname>constraint on <property>name</property>. Since no group is
specified for this annotation its default group is
<classname>javax.validation.groups.Default</classname>.</para>
<note>
<para>When more than one group is requested, the order in which the
groups are evaluated is not deterministic. If no group is specified the
default group <classname>javax.validation.groups.Default</classname> is
assumed.</para>
</note>
<example id="example-person">
<title>Person</title>
<programlisting language="JAVA" role="JAVA">public class Person {
@NotNull
private String name;
public Person(String name) {
this.name = name;
}
// getters and setters ...
}</programlisting>
</example>
<para>Next we have the class <classname>Driver</classname> (<xref
linkend="example-driver" />) extending <classname>Person</classname>. Here
we are adding the properties <property>age</property> and
<property>hasDrivingLicense</property>. In order to drive you must be at
least 18 (<classname>@Min(18)</classname>) and you must have a driving
license (<classname>@AssertTrue</classname>). Both constraints defined on
these properties belong to the group <classname>DriverChecks</classname>.
As you can see in <xref linkend="example-group-interfaces" /> the group
<classname>DriverChecks</classname> is just a simple tagging interface.
Using interfaces makes the usage of groups type safe and allows for easy
refactoring. It also means that groups can inherit from each other via
class inheritance.</para>
<example id="example-driver">
<title>Driver</title>
<programlisting language="JAVA" role="JAVA">public class Driver extends Person {
@Min(value = 18, message = "You have to be 18 to drive a car", groups = DriverChecks.class)
public int age;
@AssertTrue(message = "You first have to pass the driving test", groups = DriverChecks.class)
public boolean hasDrivingLicense;
public Driver(String name) {
super( name );
}
public void passedDrivingTest(boolean b) {
hasDrivingLicense = b;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}</programlisting>
</example>
<example id="example-group-interfaces">
<title>Group interfaces</title>
<programlisting language="JAVA" role="JAVA">public interface DriverChecks {
}
public interface CarChecks {
}</programlisting>
</example>
<para>Last but not least we add the property
<property>passedVehicleInspection</property> to the
<classname>Car</classname> class (<xref linkend="example-car" />)
indicating whether a car passed the road worthy tests.</para>
<example id="example-car">
<title>Car</title>
<programlisting language="JAVA" role="JAVA">public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
@AssertTrue(message = "The car has to pass the vehicle inspection first", groups = CarChecks.class)
private boolean passedVehicleInspection;
@Valid
private Driver driver;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
}</programlisting>
</example>
<para>Overall three different groups are used in our example.
<property>Person.name</property>, <property>Car.manufacturer</property>,
<property>Car.licensePlate</property> and
<property>Car.seatCount</property> all belong to the
<classname>Default</classname> group. <property>Driver.age</property> and
<property>Driver.hasDrivingLicense</property> belong to
<classname>DriverChecks</classname> and last but not least
<property>Car.passedVehicleInspection</property> belongs to the group
<classname>CarChecks</classname>. <xref linkend="example-drive-away" />
shows how passing different group combinations to the
<methodname>Validator.validate</methodname> method result in different
validation results.</para>
<example id="example-drive-away">
<title>Drive away</title>
<programlisting language="JAVA" role="JAVA">public class GroupTest {
private static Validator validator;
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void driveAway() {
// create a car and check that everything is ok with it.
Car car = new Car( "Morris", "DD-AB-123", 2 );
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
assertEquals( 0, constraintViolations.size() );
// but has it passed the vehicle inspection?
constraintViolations = validator.validate( car, CarChecks.class );
assertEquals( 1, constraintViolations.size() );
assertEquals("The car has to pass the vehicle inspection first", constraintViolations.iterator().next().getMessage());
// let's go to the vehicle inspection
car.setPassedVehicleInspection( true );
assertEquals( 0, validator.validate( car ).size() );
// now let's add a driver. He is 18, but has not passed the driving test yet
Driver john = new Driver( "John Doe" );
john.setAge( 18 );
car.setDriver( john );
constraintViolations = validator.validate( car, DriverChecks.class );
assertEquals( 1, constraintViolations.size() );
assertEquals( "You first have to pass the driving test", constraintViolations.iterator().next().getMessage() );
// ok, John passes the test
john.passedDrivingTest( true );
assertEquals( 0, validator.validate( car, DriverChecks.class ).size() );
// just checking that everything is in order now
assertEquals( 0, validator.validate( car, Default.class, CarChecks.class, DriverChecks.class ).size() );
}
}</programlisting>
</example>
<para>First we create a car and validate it using no explicit group. There
are no validation errors, even though the property
<property>passedVehicleInspection</property> is per default
<constant>false</constant>. However, the constraint defined on this
property does not belong to the default group. Next we just validate the
<classname>CarChecks</classname> group which will fail until we make sure
that the car passes the vehicle inspection. When we then add a driver to
the car and validate against <classname>DriverChecks</classname> we get
again a constraint violation due to the fact that the driver has not yet
passed the driving test. Only after setting
<property>passedDrivingTest</property> to true the validation against
<classname>DriverChecks</classname> will pass.</para>
<para>Last but not least, we show that all constraints are passing by
validating against all defined groups.</para>
<section>
<title>Group sequences</title>
<para>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 constraint evaluation.
In our example from <xref
linkend="validator-usingvalidator-validationgroups" /> we could for
example require that first all default car constraints are passing
before we check the road worthiness of the car. Finally before we drive
away we check the actual driver constraints. In order to implement such
an order one would define a new interface and annotate it with
<classname>@GroupSequence</classname> defining the order in which the
groups have to be validated.</para>
<note>
<para>If at least one constraints fails in a sequenced group none of
the constraints of the following groups in the sequence get
validated.</para>
</note>
<example>
<title>Interface with @GroupSequence</title>
<programlisting language="JAVA" role="JAVA">@GroupSequence({Default.class, CarChecks.class, DriverChecks.class})
public interface OrderedChecks {
}</programlisting>
</example>
<para><warning>
<para>Groups defining a sequence and groups composing a sequence
must not be involved in a cyclic dependency either directly or
indirectly, either through cascaded sequence definition or group
inheritance. If a group containing such a circularity is evaluated,
a <classname>GroupDefinitionException</classname> is raised.</para>
</warning>The usage of the new sequence could then look like in <xref
linkend="example-group-sequence" />.</para>
<example id="example-group-sequence">
<title>Usage of a group sequence</title>
<programlisting language="JAVA" role="JAVA">@Test
public void testOrderedChecks() {
Car car = new Car( "Morris", "DD-AB-123", 2 );
car.setPassedVehicleInspection( true );
Driver john = new Driver( "John Doe" );
john.setAge( 18 );
john.passedDrivingTest( true );
car.setDriver( john );
assertEquals( 0, validator.validate( car, OrderedChecks.class ).size() );
}</programlisting>
</example>
</section>
<section id="section-default-group-class">
<title>Redefining the default group sequence of a class</title>
<section>
<title>@GroupSequence</title>
<para>The <classname>@GroupSequence</classname> annotation also
fulfills a second purpose. It allows you to redefine what the
<constant>Default</constant> group means for a given class. To
redefine <classname>Default</classname> for a given class, add a
<classname>@GroupSequence</classname> annotation to the class. The
defined groups in the annotation express the sequence of groups that
substitute <classname>Default</classname> for this class. <xref
linkend="example-rental-car" /> introduces a new class
<classname>RentalCar</classname> with a redefined default group. With
this definition the check for all three groups can be rewritten as
seen in <xref
linkend="example-testOrderedChecksWithRedefinedDefault" />.</para>
<example id="example-rental-car">
<title>RentalCar with @GroupSequence</title>
<programlisting language="JAVA" role="JAVA">@GroupSequence({ RentalCar.class, CarChecks.class, DriverChecks.class })
public class RentalCar extends Car {
private boolean rented;
public RentalCar(String manufacturer, String licencePlate, int seatCount) {
super( manufacturer, licencePlate, seatCount );
}
public boolean isRented() {
return rented;
}
public void setRented(booelan rented) {
this.rented = rented;
}
}</programlisting>
</example>
<example id="example-testOrderedChecksWithRedefinedDefault">
<title>testOrderedChecksWithRedefinedDefault</title>
<programlisting language="JAVA" role="JAVA">@Test
public void testOrderedChecksWithRedefinedDefault() {
RentalCar rentalCar = new RentalCar( "Morris", "DD-AB-123", 2 );
rentalCar.setPassedVehicleInspection( true );
Driver john = new Driver( "John Doe" );
john.setAge( 18 );
john.passedDrivingTest( true );
rentalCar.setDriver( john );
assertEquals( 0, validator.validate( rentalCar, Default.class ).size() );
}</programlisting>
</example>
<note>
<para>Due to the fact that there cannot be a cyclic dependency in
the group and group sequence definitions one cannot just add
<classname>Default</classname> to the sequence redefining
<classname>Default</classname> for a class. Instead the class itself
should be added!</para>
</note>