| 1 |
[[validator-gettingstarted]] |
| 2 |
== Getting started |
| 3 |
|
| 4 |
This chapter will show you how to get started with Hibernate Validator, the reference implementation (RI) of Bean Validation. For the following quick-start you need: |
| 5 |
|
| 6 |
* A JDK >= 6 |
| 7 |
* http://maven.apache.org/[Apache Maven] |
| 8 |
* An Internet connection (Maven has to download all required libraries) |
| 9 |
|
| 10 |
[[validator-gettingstarted-createproject]] |
| 11 |
=== Project set up |
| 12 |
|
| 13 |
In order to use Hibernate Validator within a Maven project, simply add the following dependency to |
| 14 |
your __pom.xml__: |
| 15 |
|
| 16 |
.Hibernate Validator Maven dependency |
| 17 |
==== |
| 18 |
[source, XML] |
| 19 |
[subs="verbatim,attributes"] |
| 20 |
---- |
| 21 |
<dependency> |
| 22 |
<groupId>org.hibernate</groupId> |
| 23 |
<artifactId>hibernate-validator</artifactId> |
| 24 |
<version>{hvVersion}</version> |
| 25 |
</dependency> |
| 26 |
---- |
| 27 |
==== |
| 28 |
|
| 29 |
This transitively pulls in the dependency to the Bean Validation API |
| 30 |
(`javax.validation:validation-api:{bvVersion}`). |
| 31 |
|
| 32 |
[[validator-gettingstarted-uel]] |
| 33 |
==== Unified EL |
| 34 |
|
| 35 |
Hibernate Validator requires an implementation of the Unified Expression Language |
| 36 |
(http://jcp.org/en/jsr/detail?id=341[JSR 341]) for evaluating dynamic expressions in constraint |
| 37 |
violation messages (see <<section-message-interpolation>>). When your application runs in a Java EE |
| 38 |
container such as JBoss AS, an EL implementation is already provided by the container. In a Java SE |
| 39 |
environment, however, you have to add an implementation as dependency to your POM file. For instance |
| 40 |
you can add the following two dependencies to use the JSR 341 http://uel.java.net/[reference |
| 41 |
implementation]: |
| 42 |
|
| 43 |
.Maven dependencies for Unified EL reference implementation |
| 44 |
==== |
| 45 |
[source, XML] |
| 46 |
---- |
| 47 |
<dependency> |
| 48 |
<groupId>javax.el</groupId> |
| 49 |
<artifactId>javax.el-api</artifactId> |
| 50 |
<version>2.2.4</version> |
| 51 |
</dependency> |
| 52 |
<dependency> |
| 53 |
<groupId>org.glassfish.web</groupId> |
| 54 |
<artifactId>javax.el</artifactId> |
| 55 |
<version>2.2.4</version> |
| 56 |
</dependency> |
| 57 |
---- |
| 58 |
==== |
| 59 |
|
| 60 |
[TIP] |
| 61 |
==== |
| 62 |
For environments where one cannot provide a EL implementation Hibernate Validator is offering a |
| 63 |
<<non-el-message-interpolator>>. However, the use of this interpolator |
| 64 |
is not Bean Validation specification compliant. |
| 65 |
==== |
| 66 |
|
| 67 |
[[section-getting-started-cdi]] |
| 68 |
==== CDI |
| 69 |
|
| 70 |
Bean Validation defines integration points with CDI (Contexts and Dependency Injection for Java ^TM^ |
| 71 |
EE, http://jcp.org/en/jsr/detail?id=346[JSR 346]). If your application runs in an |
| 72 |
environment which does not provide this integration out of the box, you may use the Hibernate |
| 73 |
Validator CDI portable extension by adding the following Maven dependency to your POM: |
| 74 |
|
| 75 |
.Hibernate Validator CDI portable extension Maven dependency |
| 76 |
==== |
| 77 |
[source, XML] |
| 78 |
[subs="verbatim,attributes"] |
| 79 |
---- |
| 80 |
<dependency> |
| 81 |
<groupId>org.hibernate</groupId> |
| 82 |
<artifactId>hibernate-validator-cdi</artifactId> |
| 83 |
<version>{hvVersion}</version> |
| 84 |
</dependency> |
| 85 |
---- |
| 86 |
==== |
| 87 |
|
| 88 |
Note that adding this dependency is usually not required for applications running on a Java EE |
| 89 |
application server. You can learn more about the integration of Bean Validation and CDI in |
| 90 |
<<section-integration-with-cdi>>. |
| 91 |
|
| 92 |
[[section-getting-started-security-manager]] |
| 93 |
==== Running with a security manager |
| 94 |
|
| 95 |
Hibernate Validator supports running with a http://docs.oracle.com/javase/8/docs/technotes/guides/security/index.html[security manager] being enabled. |
| 96 |
To do so, you must assign several permissions to the Hibernate Validator and the Bean Validation API code bases. |
| 97 |
The following shows how to do this via a http://docs.oracle.com/javase/8/docs/technotes/guides/security/PolicyFiles.html[policy file] as processed by the Java default policy implementation: |
| 98 |
|
| 99 |
.Policy file for using Hibernate Validator with a security manager |
| 100 |
==== |
| 101 |
[source, XML] |
| 102 |
[subs="verbatim,attributes"] |
| 103 |
---- |
| 104 |
grant codeBase "file:path/to/hibernate-validator-{hvVersion}.jar" { |
| 105 |
permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; |
| 106 |
permission java.lang.RuntimePermission "accessDeclaredMembers"; |
| 107 |
permission java.lang.RuntimePermission "setContextClassLoader"; |
| 108 |
|
| 109 |
permission org.hibernate.validator.HibernateValidatorPermission "accessPrivateMembers"; |
| 110 |
|
| 111 |
// Only needed when working with XML descriptors (validation.xml or XML constraint mappings) |
| 112 |
permission java.util.PropertyPermission "mapAnyUriToUri", "read"; |
| 113 |
}; |
| 114 |
|
| 115 |
grant codeBase "file:path/to/validation-api-{bvVersion}.jar" { |
| 116 |
permission java.io.FilePermission "path/to/hibernate-validator-{hvVersion}.jar", "read"; |
| 117 |
}; |
| 118 |
---- |
| 119 |
==== |
| 120 |
|
| 121 |
All API invocations requiring special permissions are done via privileged actions. |
| 122 |
This means only Hibernate Validator and the Bean Validation API themselves need the listed permissions. |
| 123 |
You don't need to assign any permissions to other code bases calling Hibernate Validator. |
| 124 |
|
| 125 |
[[validator-gettingstarted-createmodel]] |
| 126 |
=== Applying constraints |
| 127 |
|
| 128 |
Lets dive directly into an example to see how to apply constraints. |
| 129 |
|
| 130 |
[[example-class-car]] |
| 131 |
.Class Car annotated with constraints |
| 132 |
==== |
| 133 |
[source, JAVA] |
| 134 |
---- |
| 135 |
package org.hibernate.validator.referenceguide.chapter01; |
| 136 |
|
| 137 |
import javax.validation.constraints.Min; |
| 138 |
import javax.validation.constraints.NotNull; |
| 139 |
import javax.validation.constraints.Size; |
| 140 |
|
| 141 |
public class Car { |
| 142 |
|
| 143 |
@NotNull |
| 144 |
private String manufacturer; |
| 145 |
|
| 146 |
@NotNull |
| 147 |
@Size(min = 2, max = 14) |
| 148 |
private String licensePlate; |
| 149 |
|
| 150 |
@Min(2) |
| 151 |
private int seatCount; |
| 152 |
|
| 153 |
public Car(String manufacturer, String licencePlate, int seatCount) { |
| 154 |
this.manufacturer = manufacturer; |
| 155 |
this.licensePlate = licencePlate; |
| 156 |
this.seatCount = seatCount; |
| 157 |
} |
| 158 |
|
| 159 |
//getters and setters ... |
| 160 |
} |
| 161 |
---- |
| 162 |
==== |
| 163 |
|
| 164 |
The `@NotNull`, `@Size` and `@Min` annotations are used to declare the constraints which should be applied |
| 165 |
to the fields of a Car instance: |
| 166 |
|
| 167 |
|
| 168 |
* `manufacturer` must never be `null` |
| 169 |
* `licensePlate` must never be `null` and must be between 2 and 14 characters long |
| 170 |
* `seatCount` must be at least 2 |
| 171 |
|
| 172 |
[TIP] |
| 173 |
==== |
| 174 |
You can find the complete source code of all examples used in this reference guide in the Hibernate |
| 175 |
Validator |
| 176 |
https://github.com/hibernate/hibernate-validator/tree/master/documentation/src/test[source repository] |
| 177 |
on GitHub. |
| 178 |
==== |
| 179 |
|
| 180 |
=== Validating constraints |
| 181 |
|
| 182 |
To perform a validation of these constraints, you use a `Validator` instance. Let's have a look at a |
| 183 |
unit test for `Car`: |
| 184 |
|
| 185 |
.Class CarTest showing validation examples |
| 186 |
==== |
| 187 |
[source, JAVA] |
| 188 |
---- |
| 189 |
package org.hibernate.validator.referenceguide.chapter01; |
| 190 |
|
| 191 |
import java.util.Set; |
| 192 |
import javax.validation.ConstraintViolation; |
| 193 |
import javax.validation.Validation; |
| 194 |
import javax.validation.Validator; |
| 195 |
import javax.validation.ValidatorFactory; |
| 196 |
|
| 197 |
import org.junit.BeforeClass; |
| 198 |
import org.junit.Test; |
| 199 |
|
| 200 |
import static org.junit.Assert.assertEquals; |
| 201 |
|
| 202 |
public class CarTest { |
| 203 |
|
| 204 |
private static Validator validator; |
| 205 |
|
| 206 |
@BeforeClass |
| 207 |
public static void setUpValidator() { |
| 208 |
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); |
| 209 |
validator = factory.getValidator(); |
| 210 |
} |
| 211 |
|
| 212 |
@Test |
| 213 |
public void manufacturerIsNull() { |
| 214 |
Car car = new Car( null, "DD-AB-123", 4 ); |
| 215 |
|
| 216 |
Set<ConstraintViolation<Car>> constraintViolations = |
| 217 |
validator.validate( car ); |
| 218 |
|
| 219 |
assertEquals( 1, constraintViolations.size() ); |
| 220 |
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() ); |
| 221 |
} |
| 222 |
|
| 223 |
@Test |
| 224 |
public void licensePlateTooShort() { |
| 225 |
Car car = new Car( "Morris", "D", 4 ); |
| 226 |
|
| 227 |
Set<ConstraintViolation<Car>> constraintViolations = |
| 228 |
validator.validate( car ); |
| 229 |
|
| 230 |
assertEquals( 1, constraintViolations.size() ); |
| 231 |
assertEquals( |
| 232 |
"size must be between 2 and 14", |
| 233 |
constraintViolations.iterator().next().getMessage() |
| 234 |
); |
| 235 |
} |
| 236 |
|
| 237 |
@Test |
| 238 |
public void seatCountTooLow() { |
| 239 |
Car car = new Car( "Morris", "DD-AB-123", 1 ); |
| 240 |
|
| 241 |
Set<ConstraintViolation<Car>> constraintViolations = |
| 242 |
validator.validate( car ); |
| 243 |
|
| 244 |
assertEquals( 1, constraintViolations.size() ); |
| 245 |
assertEquals( |
| 246 |
"must be greater than or equal to 2", |
| 247 |
constraintViolations.iterator().next().getMessage() |
| 248 |
); |
| 249 |
} |
| 250 |
|
| 251 |
@Test |
| 252 |
public void carIsValid() { |
| 253 |
Car car = new Car( "Morris", "DD-AB-123", 2 ); |
| 254 |
|
| 255 |
Set<ConstraintViolation<Car>> constraintViolations = |
| 256 |
validator.validate( car ); |
| 257 |
|
| 258 |
assertEquals( 0, constraintViolations.size() ); |
| 259 |
} |
| 260 |
} |
| 261 |
---- |
| 262 |
==== |
| 263 |
|
| 264 |
In the `setUp()` method a `Validator` object is retrieved from the `ValidatorFactory`. A `Validator` |
| 265 |
instance is thread-safe and may be reused multiple times. It thus can safely be stored in a static |
| 266 |
field and be used in the test methods to validate the different `Car` instances. |
| 267 |
|
| 268 |
The `validate()` method returns a set of `ConstraintViolation` instances, which you can iterate over in |
| 269 |
order to see which validation errors occurred. The first three test methods show some expected |
| 270 |
constraint violations: |
| 271 |
|
| 272 |
|
| 273 |
* The `@NotNull` constraint on `manufacturer` is violated in `manufacturerIsNull()` |
| 274 |
* The `@Size` constraint on `licensePlate` is violated in `licensePlateTooShort()` |
| 275 |
* The `@Min` constraint on `seatCount` is violated in `seatCountTooLow()` |
| 276 |
|
| 277 |
If the object validates successfully, `validate()` returns an empty set as you can see in `carIsValid()`. |
| 278 |
|
| 279 |
Note that only classes from the package `javax.validation` are used. These are provided from the Bean |
| 280 |
Validation API. No classes from Hibernate Validator are directly referenced, resulting in portable |
| 281 |
code. |
| 282 |
|
| 283 |
=== Java 8 support |
| 284 |
|
| 285 |
Java 8 introduces several enhancements which are valuable from a Hibernate Validator point of view. |
| 286 |
This section briefly introduces the Hibernate Validator features based on Java 8. |
| 287 |
They are only available in Hibernate Validator 5.2 and later. |
| 288 |
|
| 289 |
==== Type arguments constraints |
| 290 |
|
| 291 |
In Java 8 it is possible to use annotations in any location a type is used. This includes type |
| 292 |
arguments. Hibernate Validator supports the validation of constraints defined on type arguments |
| 293 |
of collections, maps, and custom parameterized types. The <<type-arguments-constraints>> chapter |
| 294 |
provides further information on how to apply and use type argument constraints. |
| 295 |
|
| 296 |
==== Actual parameter names |
| 297 |
|
| 298 |
The Java 8 Reflection API can now retrieve the actual parameter names of a method or constructor. |
| 299 |
Hibernate Validator uses this ability to report the actual parameter names instead of `arg0`, |
| 300 |
`arg1`, etc. The <<section-parameter-name-provider>> chapter explains how to use the new reflection |
| 301 |
based parameter name provider. |
| 302 |
|
| 303 |
==== New date/time API |
| 304 |
|
| 305 |
Java 8 introduces a new date/time API. Hibernate Validator provides full support for the new API |
| 306 |
where `@Future` and `@Past` constraints can be applied on the new types. The table |
| 307 |
<<table-spec-constraints>> shows the types supported for `@Future` and `@Past`, including the types |
| 308 |
from the new API. |
| 309 |
|
| 310 |
==== Optional type |
| 311 |
|
| 312 |
Hibernate Validator provides also support for Java 8 `Optional` type, by unwrapping the `Optional` |
| 313 |
instance and validating the internal value. <<section-optional-unwrapper>> provides examples and a |
| 314 |
further discussion. |
| 315 |
|
| 316 |
[[validator-gettingstarted-whatsnext]] |
| 317 |
=== Where to go next? |
| 318 |
|
| 319 |
That concludes the 5 minute tour through the world of Hibernate Validator and Bean Validation. |
| 320 |
Continue exploring the code examples or look at further examples referenced in |
| 321 |
<<validator-further-reading>>. |
| 322 |
|
| 323 |
To learn more about the validation of beans and properties, just continue reading |
| 324 |
<<chapter-bean-constraints>>. If you are interested in using Bean Validation for the validation of |
| 325 |
method pre- and postcondition refer to <<chapter-method-constraints>>. In case your application has |
| 326 |
specific validation requirements have a look at <<validator-customconstraints>>. |