Debian Codegraph @

documentation/src/main/asciidoc/ch10.asciidoc

raw
1 [[validator-integration]]
2 == Integrating with other frameworks
3
4 Hibernate Validator is intended to be used to implement multi-layered data validation, where
5 constraints are expressed in a single place (the annotated domain model) and checked in various
6 different layers of the application. For this reason there are multiple integration points with
7 other technologies.
8
9 [[validator-checkconstraints-orm]]
10 === ORM integration
11
12 Hibernate Validator integrates with both Hibernate and all pure Java Persistence providers.
13
14 [TIP]
15 ====
16 When lazy loaded associations are supposed to be validated it is recommended to place the constraint
17 on the getter of the association. Hibernate replaces lazy loaded associations with proxy instances
18 which get initialized/loaded when requested via the getter. If, in such a case, the constraint is
19 placed on field level the actual proxy instance is used which will lead to validation errors.
20 ====
21
22 [[validator-checkconstraints-db]]
23 ==== Database schema-level validation
24
25 Out of the box, Hibernate (as of version 3.5.x) will translate the constraints you have defined for
26 your entities into mapping metadata. For example, if a property of your entity is annotated
27 `@NotNull`, its columns will be declared as `not null` in the DDL schema generated by Hibernate.
28
29 If, for some reason, the feature needs to be disabled, set `hibernate.validator.apply_to_ddl` to
30 `false`. See also <<table-spec-constraints>> and <<table-custom-constraints>>.
31
32 You can also limit the DDL constraint generation to a subset of the defined constraints by setting
33 the property `org.hibernate.validator.group.ddl`. The property specifies the comma-separated, fully
34 specified class names of the groups a constraint has to be part of in order to be considered for DDL
35 schema generation.
36
37 [[validator-checkconstraints-orm-hibernateevent]]
38 ==== Hibernate event-based validation
39
40 Hibernate Validator has a built-in Hibernate event listener -
41 `https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/BeanValidationEventListener.java[org.hibernate.cfg.beanvalidation.BeanValidationEventListener]` -
42 which is part of Hibernate ORM. Whenever a `PreInsertEvent`,
43 `PreUpdateEvent` or `PreDeleteEvent` occurs, the listener will verify all constraints of the entity
44 instance and throw an exception if any constraint is violated. Per default objects will be checked
45 before any inserts or updates are made by Hibernate. Pre deletion events will per default not
46 trigger a validation. You can configure the groups to be validated per event type using the
47 properties `javax.persistence.validation.group.pre-persist`,
48 `javax.persistence.validation.group.pre-update` and `javax.persistence.validation.group.pre-remove`.
49 The values of these properties are the comma-separated, fully specified class names of the groups
50 to validate. <<example-beanvalidationeventlistener-config>> shows the default values for these
51 properties. In this case they could also be omitted.
52
53 On constraint violation, the event will raise a runtime `ConstraintViolationException` which contains
54 a set of `ConstraintViolation` instances describing each failure.
55
56 If Hibernate Validator is present in the classpath, Hibernate ORM will use it transparently.
57 To avoid validation even though Hibernate Validator is in the classpath set
58 `javax.persistence.validation.mode` to none.
59
60 [NOTE]
61 ====
62 If the beans are not annotated with validation annotations, there is no runtime performance cost.
63 ====
64
65 In case you need to manually set the event listeners for Hibernate ORM, use the following
66 configuration in _hibernate.cfg.xml_:
67
68 [[example-beanvalidationeventlistener-config]]
69 .Manual configuration of `BeanValidationEvenListener`
70 ====
71 [source, XML]
72 ----
73 <hibernate-configuration>
74 <session-factory>
75 ...
76 <property name="javax.persistence.validation.group.pre-persist">
77 javax.validation.groups.Default
78 </property>
79 <property name="javax.persistence.validation.group.pre-update">
80 javax.validation.groups.Default
81 </property>
82 <property name="javax.persistence.validation.group.pre-remove"></property>
83 ...
84 <event type="pre-update">
85 <listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/>
86 </event>
87 <event type="pre-insert">
88 <listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/>
89 </event>
90 <event type="pre-delete">
91 <listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/>
92 </event>
93 </session-factory>
94 </hibernate-configuration>
95 ----
96 ====
97
98 ==== JPA
99
100 If you are using JPA 2 and Hibernate Validator is in the classpath the JPA2 specification requires
101 that Bean Validation gets enabled. The properties `javax.persistence.validation.group.pre-persist`,
102 `javax.persistence.validation.group.pre-update` and `javax.persistence.validation.group.pre-remove` as
103 described in <<validator-checkconstraints-orm-hibernateevent>> can in this case be configured in
104 _persistence.xml_. _persistence.xml_ also defines a node validation-mode which can be set to `AUTO`,
105 `CALLBACK`, `NONE`. The default is `AUTO`.
106
107 In a JPA 1 you will have to create and register Hibernate Validator yourself. In case you are using
108 Hibernate EntityManager you can add a customized version of the `BeanValidationEventListener`
109 described in <<validator-checkconstraints-orm-hibernateevent>> to your project and register it
110 manually.
111
112 [[section-presentation-layer]]
113
114 === JSF & Seam
115
116 When working with JSF2 or JBoss Seam and Hibernate Validator (Bean Validation) is present in the
117 runtime environment, validation is triggered for every field in the application. <<example-jsf2>>
118 shows an example of the `f:validateBean` tag in a JSF page. The `validationGroups` attribute is optional
119 and can be used to specify a comma separated list of validation groups. The default is
120 `javax.validation.groups.Default`. For more information refer to the Seam documentation or the JSF 2
121 specification.
122
123
124 [[example-jsf2]]
125 .Usage of Bean Validation within JSF2
126 ====
127 [source, XML]
128 ----
129 <h:form>
130
131 <f:validateBean validationGroups="javax.validation.groups.Default">
132
133 <h:inputText value=#{model.property}/>
134 <h:selectOneRadio value=#{model.radioProperty}> ... </h:selectOneRadio>
135 <!-- other input components here -->
136
137 </f:validateBean>
138
139 </h:form>
140 ----
141 ====
142
143 [TIP]
144 ====
145 The integration between JSF 2 and Bean Validation is described in the "Bean Validation Integration"
146 chapter of link:$$http://jcp.org/en/jsr/detail?id=314$$[JSR-314]. It is interesting to know that JSF
147 2 implements a custom `MessageInterpolator` to ensure ensure proper localization. To encourage the use
148 of the Bean Validation message facility, JSF 2 will per default only display the generated Bean
149 Validation message. This can, however, be configured via the application resource bundle by
150 providing the following configuration (`{0}` is replaced with the Bean Validation message and `{1}` is
151 replaced with the JSF component label):
152
153 ----
154 javax.faces.validator.BeanValidator.MESSAGE={1}: {0}
155 ----
156
157 The default is:
158
159 ----
160 javax.faces.validator.BeanValidator.MESSAGE={0}
161 ----
162 ====
163
164
165 [[section-integration-with-cdi]]
166 === CDI
167
168 As of version 1.1, Bean Validation is integrated with CDI (Contexts and Dependency Injection for
169 Java^TM^ EE).
170
171 This integration provides CDI managed beans for `Validator` and `ValidatorFactory` and enables
172 dependency injection in constraint validators as well as custom message interpolators, traversable
173 resolvers, constraint validator factories and parameter name providers.
174
175 Furthermore, parameter and return value constraints on the methods and constructors of CDI managed
176 beans will automatically be validated upon invocation.
177
178 When your application runs on a Jave EE container, this integration is enabled by default. When
179 working with CDI in a Servlet container or in a pure Java SE environment, you can use the CDI
180 portable extension provided by Hibernate Validator. To do so, add the portable extension to your
181 class path as described in <<section-getting-started-cdi>>.
182
183 ==== Dependency injection
184
185 CDI's dependency injection mechanism makes it very easy to retrieve `ValidatorFactory` and `Validator`
186 instances and use them in your managed beans. Just annotate instance fields of your bean with
187 `@javax.inject.Inject` as shown in <<example-dependency-injection>>.
188
189 [[example-dependency-injection]]
190 .Retrieving validator factory and validator via `@Inject`
191 ====
192 [source, JAVA]
193 ----
194 package org.hibernate.validator.referenceguide.chapter10.cdi.validator;
195
196 @ApplicationScoped
197 public class RentalStation {
198
199 @Inject
200 private ValidatorFactory validatorFactory;
201
202 @Inject
203 private Validator validator;
204
205 //...
206 }
207 ----
208 ====
209
210 The injected beans are the default validator factory and validator instances. In order to configure
211 them - e.g. to use a custom message interpolator - you can use the Bean Validation XML descriptors
212 as discussed in <<chapter-xml-configuration>>.
213
214 If you are working with several Bean Validation providers you can make sure that factory and
215 validator from Hibernate Validator are injected by annotating the injection points with the
216 `@HibernateValidator` qualifier which is demonstrated in <<example-dependency-injection-using-hv>>.
217
218 [[example-dependency-injection-using-hv]]
219 .Using the `@HibernateValidator` qualifier annotation
220 ====
221 [source, JAVA]
222 ----
223 package org.hibernate.validator.referenceguide.chapter10.cdi.validator.qualifier;
224
225 @ApplicationScoped
226 public class RentalStation {
227
228 @Inject
229 @HibernateValidator
230 private ValidatorFactory validatorFactory;
231
232 @Inject
233 @HibernateValidator
234 private Validator validator;
235
236 //...
237 }
238 ----
239 ====
240
241 [TIP]
242 ====
243 The fully-qualified name of the qualifier annotation is
244 `org.hibernate.validator.cdi.HibernateValidator`. Be sure to not import
245 `org.hibernate.validator.HibernateValidator` instead which is the `ValidationProvider` implementation
246 used for selecting Hibernate Validator when working with the bootstrapping API (see
247 <<section-retrieving-validator-factory-validator>>).
248 ====
249
250 Via `@Inject` you also can inject dependencies into constraint validators and other Bean Validation
251 objects such as `MessageInterpolator` implementations etc.
252
253 <<example-constraint-validator-injected-bean>>
254 demonstrates how an injected CDI bean is used in a `ConstraintValidator` implementation to determine
255 whether the given constraint is valid or not. As the example shows, you also can work with the
256 `@PostConstruct` and `@PreDestroy` callbacks to implement any required construction and destruction
257 logic.
258
259 [[example-constraint-validator-injected-bean]]
260 .Constraint validator with injected bean
261 ====
262 [source, JAVA]
263 ----
264 package org.hibernate.validator.referenceguide.chapter10.cdi.injection;
265
266 public class ValidLicensePlateValidator
267 implements ConstraintValidator<ValidLicensePlate, String> {
268
269 @Inject
270 private VehicleRegistry vehicleRegistry;
271
272 @PostConstruct
273 public void postConstruct() {
274 //do initialization logic...
275 }
276
277 @PreDestroy
278 public void preDestroy() {
279 //do destruction logic...
280 }
281
282 @Override
283 public void initialize(ValidLicensePlate constraintAnnotation) {
284 }
285
286 @Override
287 public boolean isValid(String licensePlate, ConstraintValidatorContext constraintContext) {
288 return vehicleRegistry.isValidLicensePlate( licensePlate );
289 }
290 }
291 ----
292 ====
293
294 ==== Method validation
295
296 The method interception facilities of CDI allow for a very tight integration with Bean Validation's
297 method validation functionality. Just put constraint annotations to the parameters and return values
298 of the executables of your CDI beans and they will be validated automatically before (parameter
299 constraints) and after (return value constraints) a method or constructor is invoked.
300
301 Note that no explicit interceptor binding is required, instead the required method validation
302 interceptor will automatically be registered for all managed beans with constrained methods and
303 constructors.
304
305 [NOTE]
306 ====
307 The interceptor `org.hibernate.validator.internal.cdi.interceptor.ValidationInterceptor` is
308 registered by `org.hibernate.validator.internal.cdi.ValidationExtension`. This happens implicitly
309 within a Java EE 7 runtime environment or explicitly by adding the _hibernate-validator-cdi_ artifact
310 - see <<section-getting-started-cdi>>
311 ====
312
313 You can see an example in <<example-cdi-method-validation>>.
314
315 [[example-cdi-method-validation]]
316 .CDI managed beans with method-level constraints
317 ====
318 [source, JAVA]
319 ----
320 package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation;
321
322 @ApplicationScoped
323 public class RentalStation {
324
325 @Valid
326 public RentalStation() {
327 //...
328 }
329
330 @NotNull
331 @Valid
332 public Car rentCar(
333 @NotNull Customer customer,
334 @NotNull @Future Date startDate,
335 @Min(1) int durationInDays) {
336 //...
337 }
338
339 @NotNull
340 List<Car> getAvailableCars() {
341 //...
342 }
343 }
344 ----
345
346 [source, JAVA]
347 ----
348 package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation;
349
350 @RequestScoped
351 public class RentCarRequest {
352
353 @Inject
354 private RentalStation rentalStation;
355
356 public void rentCar(String customerId, Date startDate, int duration) {
357 //causes ConstraintViolationException
358 rentalStation.rentCar( null, null, -1 );
359 }
360 }
361 ----
362 ====
363
364 Here the `RentalStation` bean hosts several method constraints. When invoking one of the `RentalStation`
365 methods from another bean such as `RentCarRequest`, the constraints of the invoked method are
366 automatically validated. If any illegal parameter values are passed as in the example, a
367 `ConstraintViolationException` will be thrown by the method interceptor, providing detailed
368 information on the violated constraints. The same is the case if the method's return value violates
369 any return value constraints.
370
371 Similarly, constructor constraints are validated automatically upon invocation. In the example the
372 `RentalStation` object returned by the constructor will be validated since the constructor return
373 value is marked with `@Valid`.
374
375 ===== Validated executable types
376
377 Bean Validation allows for a fine-grained control of the executable types which are automatically
378 validated. By default, constraints on constructors and non-getter methods are validated. Therefore
379 the `@NotNull` constraint on the method `RentalStation#getAvailableCars()` in
380 <<example-cdi-method-validation>> gets not validated when the method is invoked.
381
382 You have the following options to configure which types of executables are validated upon
383 invocation:
384
385 * Configure the executable types globally via the XML descriptor __META-INF/validation.xml__;
386 see <<section-configuration-validation-xml>> for an example
387
388 * Use the `@ValidateOnExecution` annotation on the executable or type level
389
390 If several sources of configuration are specified for a given executable, `@ValidateOnExecutionn on
391 the executable level takes precedence over `@ValidateOnExecution` on the type level and
392 `@ValidateOnExecution` generally takes precedence over the globally configured types in __META-
393 INF/validation.xml__.
394
395 <<example-using-validateonexecution>> shows how to use the `@ValidateOnExecution` annotation:
396
397 [[example-using-validateonexecution]]
398 .Using `@ValidateOnExecution`
399 ====
400 [source, JAVA]
401 ----
402 package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.configuration;
403
404 @ApplicationScoped
405 @ValidateOnExecution(type = ExecutableType.ALL)
406 public class RentalStation {
407
408 @Valid
409 public RentalStation() {
410 //...
411 }
412
413 @NotNull
414 @Valid
415 @ValidateOnExecution(type = ExecutableType.NONE)
416 public Car rentCar(
417 @NotNull Customer customer,
418 @NotNull @Future Date startDate,
419 @Min(1) int durationInDays) {
420 //...
421 }
422
423 @NotNull
424 public List<Car> getAvailableCars() {
425 //...
426 }
427 }
428 ----
429 ====
430
431 Here the method `rentCar()` won't be validated upon invocation because it is annotated with
432 `@ValidateOnExecution(type = ExecutableType.NONE)`. In contrast, the constructor and the
433 method `getAvailableCars()` will be validated due to `@ValidateOnExecution(type =
434 ExecutableType.ALL)` being given on the type level. `ExecutableType.ALL` is a more compact form for
435 explicitly specifying all the types `CONSTRUCTORS`, `GETTER_METHODS` and `NON_GETTER_METHODS`.
436
437
438 [TIP]
439 ====
440 Executable validation can be turned off globally by specifying
441 `<executable-validation enabled="false"/>` in _META-INF/validation.xml_. In this case, any
442 `@ValidateOnExecution` annotations are ignored.
443 ====
444
445 Note that when a method overrides or implements a super-type method the configuration will be taken
446 from that overridden or implemented method (as given via `@ValidateOnExecution` on the method itself
447 or on the super-type). This protects a client of the super-type method from an unexpected alteration
448 of the configuration, e.g. disabling validation of an overridden executable in a sub-type.
449
450 In case a CDI managed bean overrides or implements a super-type method and this super-type method
451 hosts any constraints, it can happen that the validation interceptor is not properly registered with
452 the bean, resulting in the bean's methods not being validated upon invocation. In this case you can
453 specify the executable type `IMPLICIT` on the sub-class as shown in
454 <<example-using-executabletype-implicit>>, which makes sure that all required metadata is discovered
455 an the validation interceptor kicks in when the methods on `ExpressRentalStation` are invoked.
456
457 [[example-using-executabletype-implicit]]
458 .Using `ExecutableType.IMPLICIT`
459 ====
460 [source, JAVA]
461 ----
462 package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.implicit;
463
464 @ValidateOnExecution(type = ExecutableType.ALL)
465 public interface RentalStation {
466
467 @NotNull
468 @Valid
469 Car rentCar(
470 @NotNull Customer customer,
471 @NotNull @Future Date startDate,
472 @Min(1) int durationInDays);
473 }
474 ----
475
476
477 [source, JAVA]
478 ----
479 package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.implicit;
480
481 @ApplicationScoped
482 @ValidateOnExecution(type = ExecutableType.IMPLICIT)
483 public class ExpressRentalStation implements RentalStation {
484
485 @Override
486 public Car rentCar(Customer customer, Date startDate, @Min(1) int durationInDays) {
487 //...
488 }
489 }
490 ----
491 ====
492
493
494 === Java EE
495
496 When your application runs on a Java EE application server such as link:WildFly[http://wildfly.org/],
497 you also can obtain `Validator` and `ValidatorFactory` instances via `@Resource` injection in
498 managed objects such as EJBs etc., as shown in <<example-validator-resource-injection>>.
499
500 [[example-validator-resource-injection]]
501 .Retrieving `Validator` and `ValidatorFactory` via `@Resource` injection
502 ====
503 [source, JAVA]
504 ----
505 package org.hibernate.validator.referenceguide.chapter10.javaee;
506
507 @Stateless
508 public class RentalStationBean {
509
510 @Resource
511 private ValidatorFactory validatorFactory;
512
513 @Resource
514 private Validator validator;
515
516 //...
517 }
518 ----
519 ====
520
521 Alternatively you can obtain a validator and a validator factory from JNDI under the names
522 "_java:comp/Validator_" and "_java:comp/ValidatorFactory_", respectively.
523
524 Similar to CDI-based injection via `@Inject`, these objects represent default validator and validator
525 factory and thus can be configured using the XML descriptor _META-INF/validation.xml_ (see
526 <<chapter-xml-configuration>>).
527
528 When your application is CDI-enabled, the injected objects are CDI-aware as well and e.g. support
529 dependency injection in constraint validators.
530
531 === JavaFX
532
533 Hibernate Validator also provides support for the unwrapping of JavaFX properties. If JavaFX is present
534 on the classpath a `ValidatedValueUnwrapper` for JavaFX properties is automatically registered. In some
535 cases, however, it is also necessary to explicitly use `@UnwrapValidatedValue`. This is required if
536 the constraint validator resolution is not unique and there is a potential constraint validator for
537 the actual JavaFX property as well as the contained property value itself.
538 See <<section-javafx-unwrapper>> for examples and further discussion.