Debian Codegraph @

documentation/src/main/asciidoc/ch05.asciidoc

raw
1 [[chapter-groups]]
2 == Grouping constraints
3
4 All validation methods on `Validator` and `ExecutableValidator` discussed in earlier chapters also take
5 a var-arg argument groups. So far we have been ignoring this parameter, but it is time to have a
6 closer look.
7
8 === Requesting groups
9
10 Groups allow you to restrict the set of constraints applied during validation. One use case for
11 validation groups are UI wizards where in each step only a specified subset of constraints should
12 get validated. The groups targeted are passed as var-arg parameters to the appropriate validate
13 method.
14
15 Let's have a look at an example. The class `Person` in <<example-person>> has a `@NotNull`
16 constraint on `name`. Since no group is specified for this annotation the default group
17 `javax.validation.groups.Default` is assumed.
18
19 [NOTE]
20 ====
21 When more than one group is requested, the order in which the groups are evaluated is not
22 deterministic. If no group is specified the default group `javax.validation.groups.Default` is
23 assumed.
24 ====
25
26 [[example-person]]
27 .Example class `Person`
28 ====
29 [source, JAVA]
30 ----
31 package org.hibernate.validator.referenceguide.chapter05;
32
33 public class Person {
34
35 @NotNull
36 private String name;
37
38 public Person(String name) {
39 this.name = name;
40 }
41
42 // getters and setters ...
43 }
44 ----
45 ====
46
47 The class `Driver` in <<example-driver>> extends `Person` and adds the properties `age` and
48 `hasDrivingLicense`. Drivers must be at least 18 years old (`@Min(18)`) and have a driving license
49 (`@AssertTrue`). Both constraints defined on these properties belong to the group `DriverChecks` which
50 is just a simple tagging interface.
51
52 [TIP]
53 ====
54 Using interfaces makes the usage of groups type-safe and allows for easy refactoring. It also means
55 that groups can inherit from each other via class inheritance.
56 ====
57
58 [[example-driver]]
59 .Driver
60 ====
61 [source, JAVA]
62 ----
63 package org.hibernate.validator.referenceguide.chapter05;
64
65 public class Driver extends Person {
66
67 @Min(
68 value = 18,
69 message = "You have to be 18 to drive a car",
70 groups = DriverChecks.class
71 )
72 public int age;
73
74 @AssertTrue(
75 message = "You first have to pass the driving test",
76 groups = DriverChecks.class
77 )
78 public boolean hasDrivingLicense;
79
80 public Driver(String name) {
81 super( name );
82 }
83
84 public void passedDrivingTest(boolean b) {
85 hasDrivingLicense = b;
86 }
87
88 public int getAge() {
89 return age;
90 }
91
92 public void setAge(int age) {
93 this.age = age;
94 }
95 }
96 ----
97 [source, JAVA]
98 ----
99 package org.hibernate.validator.referenceguide.chapter05;
100
101 public interface DriverChecks {
102 }
103 ----
104 ====
105
106 Finally the class `Car` (<<example-car>>) has some constraints which are part of the default group as
107 well as `@AssertTrue` in the group `CarChecks` on the property `passedVehicleInspection` which indicates
108 whether a car passed the road worthy tests.
109
110 [[example-car]]
111 .Car
112 ====
113 [source, JAVA]
114 ----
115 package org.hibernate.validator.referenceguide.chapter05;
116
117 public class Car {
118 @NotNull
119 private String manufacturer;
120
121 @NotNull
122 @Size(min = 2, max = 14)
123 private String licensePlate;
124
125 @Min(2)
126 private int seatCount;
127
128 @AssertTrue(
129 message = "The car has to pass the vehicle inspection first",
130 groups = CarChecks.class
131 )
132 private boolean passedVehicleInspection;
133
134 @Valid
135 private Driver driver;
136
137 public Car(String manufacturer, String licencePlate, int seatCount) {
138 this.manufacturer = manufacturer;
139 this.licensePlate = licencePlate;
140 this.seatCount = seatCount;
141 }
142
143 // getters and setters ...
144 }
145 ----
146
147 [source, JAVA]
148 ----
149 package org.hibernate.validator.referenceguide.chapter05;
150
151 public interface CarChecks {
152 }
153 ----
154 ====
155
156 Overall three different groups are used in the example:
157
158 * The constraints on `Person.name`, `Car.manufacturer`, `Car.licensePlate` and `Car.seatCount`
159 all belong to the `Default` group
160 * The constraints on `Driver.age` and `Driver.hasDrivingLicense` belong to `DriverChecks`
161 * The constraint on `Car.passedVehicleInspection` belongs to the group `CarChecks`
162
163 <<example-drive-away>> shows how passing different group combinations to the `Validator#validate()`
164 method results in different validation results.
165
166 [[example-drive-away]]
167 .Using validation groups
168 ====
169 [source, JAVA]
170 ----
171 // create a car and check that everything is ok with it.
172 Car car = new Car( "Morris", "DD-AB-123", 2 );
173 Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
174 assertEquals( 0, constraintViolations.size() );
175
176 // but has it passed the vehicle inspection?
177 constraintViolations = validator.validate( car, CarChecks.class );
178 assertEquals( 1, constraintViolations.size() );
179 assertEquals(
180 "The car has to pass the vehicle inspection first",
181 constraintViolations.iterator().next().getMessage()
182 );
183
184 // let's go to the vehicle inspection
185 car.setPassedVehicleInspection( true );
186 assertEquals( 0, validator.validate( car, CarChecks.class ).size() );
187
188 // now let's add a driver. He is 18, but has not passed the driving test yet
189 Driver john = new Driver( "John Doe" );
190 john.setAge( 18 );
191 car.setDriver( john );
192 constraintViolations = validator.validate( car, DriverChecks.class );
193 assertEquals( 1, constraintViolations.size() );
194 assertEquals(
195 "You first have to pass the driving test",
196 constraintViolations.iterator().next().getMessage()
197 );
198
199 // ok, John passes the test
200 john.passedDrivingTest( true );
201 assertEquals( 0, validator.validate( car, DriverChecks.class ).size() );
202
203 // just checking that everything is in order now
204 assertEquals(
205 0, validator.validate(
206 car,
207 Default.class,
208 CarChecks.class,
209 DriverChecks.class
210 ).size()
211 );
212 ----
213 ====
214
215 The first `validate()` call in <<example-drive-away>> is done using no explicit group. There are no
216 validation errors, even though the property `passedVehicleInspection` is per default `false`. However,
217 the constraint defined on this property does not belong to the default group.
218
219 The next validation using the `CarChecks` group fails until the car passes the vehicle inspection.
220 Adding a driver to the car and validating against `DriverChecks` again yields one constraint violation
221 due to the fact that the driver has not yet passed the driving test. Only after setting
222 `passedDrivingTest` to `true` the validation against `DriverChecks` passes.
223
224 The last `validate()` call finally shows that all constraints are passing by validating against all
225 defined groups.
226
227 [[section-defining-group-sequences]]
228 === Defining group sequences
229
230 By default, constraints are evaluated in no particular order, regardless of which groups they belong
231 to. In some situations, however, it is useful to control the order constraints are evaluated.
232
233 In the example from <<example-drive-away>> it could for instance be required that first all default
234 car constraints are passing before checking the road worthiness of the car. Finally, before driving
235 away, the actual driver constraints should be checked.
236
237 In order to implement such a validation order you just need to define an interface and annotate it
238 with `@GroupSequence`, defining the order in which the groups have to be validated (see
239 <<example-defining-group-sequence>>). If at least one constraint fails in a sequenced group none of the
240 constraints of the following groups in the sequence get validated.
241
242 [[example-defining-group-sequence]]
243 .Defining a group sequence
244 ====
245 [source, JAVA]
246 ----
247 package org.hibernate.validator.referenceguide.chapter05;
248
249 @GroupSequence({ Default.class, CarChecks.class, DriverChecks.class })
250 public interface OrderedChecks {
251 }
252 ----
253 ====
254
255 [WARNING]
256 ====
257 Groups defining a sequence and groups composing a sequence must not be involved in a cyclic
258 dependency either directly or indirectly, either through cascaded sequence definition or group
259 inheritance. If a group containing such a circularity is evaluated, a `GroupDefinitionException` is
260 raised.
261 ====
262
263 You then can use the new sequence as shown in in <<example-group-sequence>>.
264
265 [[example-group-sequence]]
266 .Using a group sequence
267 ====
268 [source, JAVA]
269 ----
270 Car car = new Car( "Morris", "DD-AB-123", 2 );
271 car.setPassedVehicleInspection( true );
272
273 Driver john = new Driver( "John Doe" );
274 john.setAge( 18 );
275 john.passedDrivingTest( true );
276 car.setDriver( john );
277
278 assertEquals( 0, validator.validate( car, OrderedChecks.class ).size() );
279 ----
280 ====
281
282 [[section-default-group-class]]
283 === Redefining the default group sequence
284
285 ==== `@GroupSequence`
286
287 Besides defining group sequences, the `@GroupSequence` annotation also allows to redefine the default
288 group for a given class. To do so, just add the `@GroupSequence` annotation to the class and specify
289 the sequence of groups which substitute Default for this class within the annotation.
290
291 <<example-rental-car>> introduces a new class `RentalCar` with a redefined default group.
292
293 [[example-rental-car]]
294 .Class `RentalCar` with redefined default group
295 ====
296 [source, JAVA]
297 ----
298 package org.hibernate.validator.referenceguide.chapter05;
299
300 @GroupSequence({ RentalChecks.class, CarChecks.class, RentalCar.class })
301 public class RentalCar extends Car {
302 @AssertFalse(message = "The car is currently rented out", groups = RentalChecks.class)
303 private boolean rented;
304
305 public RentalCar(String manufacturer, String licencePlate, int seatCount) {
306 super( manufacturer, licencePlate, seatCount );
307 }
308
309 public boolean isRented() {
310 return rented;
311 }
312
313 public void setRented(boolean rented) {
314 this.rented = rented;
315 }
316 }
317 ----
318
319 [source, JAVA]
320 ----
321 package org.hibernate.validator.referenceguide.chapter05;
322
323 public interface RentalChecks {
324 }
325 ----
326 ====
327
328 With this definition you can evaluate the constraints belonging to `RentalChecks`, `CarChecks` and
329 `RentalCar` by just requesting the `Default` group as seen in <<example-testCarIsRented>>.
330
331 [[example-testCarIsRented]]
332 .Validating an object with redefined default group
333 ====
334 [source, JAVA]
335 ----
336 RentalCar rentalCar = new RentalCar( "Morris", "DD-AB-123", 2 );
337 rentalCar.setPassedVehicleInspection( true );
338 rentalCar.setRented( true );
339
340 Set<ConstraintViolation<RentalCar>> constraintViolations = validator.validate( rentalCar );
341
342 assertEquals( 1, constraintViolations.size() );
343 assertEquals(
344 "Wrong message",
345 "The car is currently rented out",
346 constraintViolations.iterator().next().getMessage()
347 );
348
349 rentalCar.setRented( false );
350 constraintViolations = validator.validate( rentalCar );
351
352 assertEquals( 0, constraintViolations.size() );
353 ----
354 ====
355
356 [NOTE]
357 ====
358 Since there must no cyclic dependency in the group and group sequence definitions one cannot just
359 add `Default` to the sequence redefining `Default` for a class. Instead the class itself has to be
360 added!
361 ====
362
363 The `Default` group sequence overriding is local to the class it is defined on and is not propagated
364 to associated objects. For the example this means that adding `DriverChecks` to the default group
365 sequence of `RentalCar` would not have any effects. Only the group `Default` will be propagated to the
366 driver association.
367
368 Note that you can control the propagated group(s) by declaring a group conversion rule (see
369 <<section-group-conversion>>).
370
371 ==== `@GroupSequenceProvider`
372
373 In addition to statically redefining default group sequences via `@GroupSequence`, Hibernate Validator
374 also provides an SPI for the dynamic redefinition of default group sequences depending on the object
375 state.
376
377 For that purpose you need to implement the interface `DefaultGroupSequenceProvider` and register this
378 implementation with the target class via the `@GroupSequenceProvider` annotation. In the rental car
379 scenario you could for instance dynamically add the `CarChecks` as seen in
380 <<example-implementing-using-default-group-sequence-provider>>.
381
382 [[example-implementing-using-default-group-sequence-provider]]
383 .Implementing and using a default group sequence provider
384 ====
385 [source, JAVA]
386 ----
387 package org.hibernate.validator.referenceguide.chapter05.groupsequenceprovider;
388
389 public class RentalCarGroupSequenceProvider
390 implements DefaultGroupSequenceProvider<RentalCar> {
391
392 @Override
393 public List<Class<?>> getValidationGroups(RentalCar car) {
394 List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
395 defaultGroupSequence.add( RentalCar.class );
396
397 if ( car != null && !car.isRented() ) {
398 defaultGroupSequence.add( CarChecks.class );
399 }
400
401 return defaultGroupSequence;
402 }
403 }
404 ----
405
406 [source, JAVA]
407 ----
408 package org.hibernate.validator.referenceguide.chapter05.groupsequenceprovider;
409
410 @GroupSequenceProvider(RentalCarGroupSequenceProvider.class)
411 public class RentalCar extends Car {
412
413 @AssertFalse(message = "The car is currently rented out", groups = RentalChecks.class)
414 private boolean rented;
415
416 public RentalCar(String manufacturer, String licencePlate, int seatCount) {
417 super( manufacturer, licencePlate, seatCount );
418 }
419
420 public boolean isRented() {
421 return rented;
422 }
423
424 public void setRented(boolean rented) {
425 this.rented = rented;
426 }
427 }
428 ----
429 ====
430
431 [[section-group-conversion]]
432 === Group conversion
433
434 What if you wanted to validate the car related checks together with the driver checks? Of course you
435 could pass the required groups to the validate call explicitly, but what if you wanted to make these
436 validations occur as part of the `Default` group validation? Here `@ConvertGroup` comes into play which
437 allows you during cascaded validation to use a different group than the originally requested one.
438
439 Let's have a look at <<example-group-conversion-dedault-to-driver-checks>>. Here `@GroupSequence({
440 CarChecks.class, Car.class })` is used to combine the car related constraints under the `Default` group
441 (see <<section-default-group-class>>). There is also a `@ConvertGroup(from = Default.class, to =
442 DriverChecks.class)` which ensures the `Default` group gets converted to the `DriverChecks` group during
443 cascaded validation of the driver association.
444
445 [[example-group-conversion-dedault-to-driver-checks]]
446 .`@ConvertGroup` usage
447 ====
448 [source, JAVA]
449 ----
450 package org.hibernate.validator.referenceguide.chapter05.groupconversion;
451
452 public class Driver {
453
454 @NotNull
455 private String name;
456
457 @Min(
458 value = 18,
459 message = "You have to be 18 to drive a car",
460 groups = DriverChecks.class
461 )
462 public int age;
463
464 @AssertTrue(
465 message = "You first have to pass the driving test",
466 groups = DriverChecks.class
467 )
468 public boolean hasDrivingLicense;
469
470 public Driver(String name) {
471 this.name = name;
472 }
473
474 public void passedDrivingTest(boolean b) {
475 hasDrivingLicense = b;
476 }
477
478 // getters and setters ...
479 }
480 ----
481
482 [source, JAVA]
483 ----
484 package org.hibernate.validator.referenceguide.chapter05.groupconversion;
485
486 @GroupSequence({ CarChecks.class, Car.class })
487 public class Car {
488
489 @NotNull
490 private String manufacturer;
491
492 @NotNull
493 @Size(min = 2, max = 14)
494 private String licensePlate;
495
496 @Min(2)
497 private int seatCount;
498
499 @AssertTrue(
500 message = "The car has to pass the vehicle inspection first",
501 groups = CarChecks.class
502 )
503 private boolean passedVehicleInspection;
504
505 @Valid
506 @ConvertGroup(from = Default.class, to = DriverChecks.class)
507 private Driver driver;
508
509 public Car(String manufacturer, String licencePlate, int seatCount) {
510 this.manufacturer = manufacturer;
511 this.licensePlate = licencePlate;
512 this.seatCount = seatCount;
513 }
514
515 // getters and setters ...
516 }
517 ----
518 ====
519
520 As a result the validation in <<example-group-conversion-test>> succeeds, even though the constraint
521 on `hasDrivingLicense` belongs to the `DriverChecks` group and only the `Default` group is requested in
522 the `validate()` call.
523
524 [[example-group-conversion-test]]
525 .Test case for `@ConvertGroup`
526 ====
527 [source, JAVA]
528 ----
529 // create a car and validate. The Driver is still null and does not get validated
530 Car car = new Car( "VW", "USD-123", 4 );
531 car.setPassedVehicleInspection( true );
532 Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
533 assertEquals( 0, constraintViolations.size() );
534
535 // create a driver who has not passed the driving test
536 Driver john = new Driver( "John Doe" );
537 john.setAge( 18 );
538
539 // now let's add a driver to the car
540 car.setDriver( john );
541 constraintViolations = validator.validate( car );
542 assertEquals( 1, constraintViolations.size() );
543 assertEquals(
544 "The driver constraint should also be validated as part of the default group",
545 constraintViolations.iterator().next().getMessage(),
546 "You first have to pass the driving test"
547 );
548 ----
549 ====
550
551 You can define group conversions wherever `@Valid` can be used, namely associations as well as method
552 and constructor parameters and return values. Multiple conversions can be specified using
553 `@ConvertGroup.List`.
554
555 However, the following restrictions apply:
556
557 * `@ConvertGroup` must only be used in combination with `@Valid`. If used without, a
558 `ConstraintDeclarationException` is thrown.
559
560 * It is not legal to have multiple conversion rules on the same element with the same from value.
561 In this case, a `ConstraintDeclarationException` is raised.
562
563 * The from attribute must not refer to a group sequence. A `ConstraintDeclarationException` is
564 raised in this situation.
565
566 [NOTE]
567 ====
568 Rules are not executed recursively. The first matching conversion rule is used and subsequent rules
569 are ignored. For example if a set of `@ConvertGroup` declarations chains group `A` to `B` and
570 `B` to `C`, the group `A` will be converted to `B` and not to `C`.
571 ====