Docsity

hibernate reference 2, Assignments of Mathematics

Partial preview of the text

Download hibernate reference 2 and more Assignments Mathematics in PDF only on Docsity!

Hibernate Validator 6.2.0.Final -

Jakarta Bean Validation Reference

Implementation

Reference Guide

Hardy Ferentschik, Gunnar Morling, Guillaume Smet

Table of Contents

Preface

Validating data is a common task that occurs throughout all application layers, from the presentation to the persistence layer. Often the same validation logic is implemented in each layer which is time consuming and error-prone. To avoid duplication of these validations, developers often bundle validation logic directly into the domain model, cluttering domain classes with validation code which is really metadata about the class itself.

Jakarta Bean Validation 2.0 - defines a metadata model and API for entity and method validation. The default metadata source are annotations, with the ability to override and extend the meta-data through the use of XML. The API is not tied to a specific application tier nor programming model. It is specifically not tied to either web or persistence tier, and is available for both server-side application programming, as well as rich client Swing application developers.

Hibernate Validator is the reference implementation of Jakarta Bean Validation. The implementation itself as well as the Jakarta Bean Validation API and TCK are all provided and distributed under the Apache Software License 2.0.

Hibernate Validator 6 and Jakarta Bean Validation 2.0 require Java 8 or later.

For environments where one cannot provide a EL implementation Hibernate Validator is offering a Section 12.10, “ParameterMessageInterpolator”. However, the use of this interpolator is not Jakarta Bean Validation specification compliant.

1.1.2. CDI

Jakarta Bean Validation defines integration points with CDI (Contexts and Dependency Injection for Jakarta EE). If your application runs in an environment which does not provide this integration out of the box, you may use the Hibernate Validator CDI portable extension by adding the following Maven dependency to your POM:

Example 1.3: Hibernate Validator CDI portable extension Maven dependency

org.hibernate.validator hibernate-validator-cdi 6.2.0.Final

Note that adding this dependency is usually not required for applications running on a Java EE application server. You can learn more about the integration of Jakarta Bean Validation and CDI in Section 11.3, “CDI”.

1.1.3. Running with a security manager

Hibernate Validator supports running with a security manager being enabled. To do so, you must assign several permissions to the code bases of Hibernate Validator, the Jakarta Bean Validation API, Classmate and JBoss Logging and also to the code base calling Jakarta Bean Validation. The following shows how to do this via a policy file as processed by the Java default policy implementation:

Example 1.4: Policy file for using Hibernate Validator with a security manager

grant codeBase "file:path/to/hibernate-validator-6.2.0.Final.jar" { permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; permission java.lang.RuntimePermission "accessDeclaredMembers"; permission java.lang.RuntimePermission "setContextClassLoader"; permission org.hibernate.validator.HibernateValidatorPermission "accessPrivateMembers"; // Only needed when working with XML descriptors (validation.xml or XML constraint mappings) permission java.util.PropertyPermission "mapAnyUriToUri", "read"; }; grant codeBase "file:path/to/jakarta.validation-api-2.0.2.jar" { permission java.io.FilePermission "path/to/hibernate-validator-6.2.0.Final.jar", "read"; }; grant codeBase "file:path/to/jboss-logging-3.4.1.Final.jar" { permission java.util.PropertyPermission "org.jboss.logging.provider", "read"; permission java.util.PropertyPermission "org.jboss.logging.locale", "read"; }; grant codeBase "file:path/to/classmate-1.5.1.jar" { permission java.lang.RuntimePermission "accessDeclaredMembers"; }; grant codeBase "file:path/to/validation-caller-x.y.z.jar" { permission org.hibernate.validator.HibernateValidatorPermission "accessPrivateMembers"; };

1.1.4. Updating Hibernate Validator in WildFly

The WildFly application server contains Hibernate Validator out of the box. In order to update the server modules for Jakarta Bean Validation API and Hibernate Validator to the latest and greatest, the patch mechanism of WildFly can be used.

You can download the patch file from SourceForge or from Maven Central using the following dependency:

Example 1.5: Maven dependency for WildFly 19.0.0.Final patch file

org.hibernate.validator hibernate-validator-modules 6.2.0.Final wildfly-19.0.0.Final-patch zip

We also provide a patch for WildFly 18.0.1.Final:

When using Hibernate Validator with CDI, be careful to not enable the java.xml.ws.annotation module of the JDK. This module contains a subset of Jakarta Annotations, but some annotations such as javax.annotation.Priority are missing. This causes the method validation interceptor of Hibernate Validator to not be registered, i.e. method validation won’t work.

Instead, add the full Jakarta Annotations API to the unnamed module (i.e. the classpath), e.g. by pulling in the jakarta.annotation:jakarta.annotation-api dependency (there already is a transitive dependency to the Jakarta Annotations API when depending on org.hibernate.validator:hibernate-validator-cdi ).

If you need to enable the java.xml.ws.annotation module for some reason, you should patch it with the contents of the full API by appending --patch -module java.xml.ws.annotation=/path/to/complete- jakarta.annotation-api.jar to your java invocation.

1.2. Applying constraints

Let’s dive directly into an example to see how to apply constraints.

Example 1.9: Class Car annotated with constraints

package org.hibernate.validator.referenceguide.chapter01; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Car { @NotNull private String manufacturer; @NotNull @Size(min = 2, max = 14) private String licensePlate; @Min(2) private int seatCount; public Car(String manufacturer, String licencePlate, int seatCount) { this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; } //getters and setters ... }

The @NotNull, @Size and @Min annotations are used to declare the constraints which should be applied to the fields of a Car instance:

  • manufacturer must never be null
  • licensePlate must never be null and must be between 2 and 14 characters long
  • seatCount must be at least 2

You can find the complete source code of all examples used in this reference guide in the Hibernate Validator source repository on GitHub.

1.3. Validating constraints

To perform a validation of these constraints, you use a Validator instance. Let’s have a look at a unit test for Car:

Example 1.10: Class CarTest showing validation examples

package org.hibernate.validator.referenceguide.chapter01; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CarTest { private static Validator validator; @BeforeClass public static void setUpValidator() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } @Test public void manufacturerIsNull() { Car car = new Car( null, "DD-AB-123", 4 ); Set<ConstraintViolation> constraintViolations = validator.validate( car ); assertEquals( 1, constraintViolations.size() ); assertEquals( "must not be null", constraintViolations.iterator().next(). getMessage() ); } @Test public void licensePlateTooShort() { Car car = new Car( "Morris", "D", 4 ); Set<ConstraintViolation> constraintViolations = validator.validate( car ); assertEquals( 1, constraintViolations.size() ); assertEquals(

14, Further reading.

To learn more about the validation of beans and properties, just continue reading Chapter 2, Declaring and validating bean constraints. If you are interested in using Jakarta Bean Validation for the validation of method pre- and postcondition refer to Chapter 3, Declaring and validating method constraints. In case your application has specific validation requirements have a look at Chapter 6, Creating custom constraints.

Chapter 2. Declaring and validating bean

constraints

In this chapter you will learn how to declare (see Section 2.1, “Declaring bean constraints”) and validate (see Section 2.2, “Validating bean constraints”) bean constraints. Section 2.3, “Built-in constraints” provides an overview of all built-in constraints coming with Hibernate Validator.

If you are interested in applying constraints to method parameters and return values, refer to Chapter 3, Declaring and validating method constraints.

2.1. Declaring bean constraints

Constraints in Jakarta Bean Validation are expressed via Java annotations. In this section you will learn how to enhance an object model with these annotations. There are four types of bean constraints:

  • field constraints
  • property constraints
  • container element constraints
  • class constraints

Not all constraints can be placed on all of these levels. In fact, none of the default constraints defined by Jakarta Bean Validation can be placed at class level. The java.lang.annotation.Target annotation in the constraint annotation itself determines on which elements a constraint can be placed. See Chapter 6, Creating custom constraints for more information.

2.1.1. Field-level constraints

Constraints can be expressed by annotating a field of a class. Example 2.1, “Field-level constraints” shows a field level configuration example:

Example 2.2: Property-level constraints

package org.hibernate.validator.referenceguide.chapter02.propertylevel; public class Car { private String manufacturer; private boolean isRegistered; public Car(String manufacturer, boolean isRegistered) { 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; } }

The property’s getter method has to be annotated, not its setter. That way also read-only properties can be constrained which have no setter method.

When using property level constraints property access strategy is used to access the value to be validated, i.e. the validation engine accesses the state via the property accessor method.

It is recommended to stick either to field or property annotations within one class. It is not recommended to annotate a field and the accompanying getter method as this would cause the field to be validated twice.

2.1.3. Container element constraints

It is possible to specify constraints directly on the type argument of a parameterized type: these constraints are called container element constraints.

This requires that ElementType.TYPE_USE is specified via @Target in the constraint definition. As of Jakarta Bean Validation 2.0, built-in Jakarta Bean Validation as well as Hibernate Validator specific constraints specify ElementType.TYPE_USE and can be used directly in this context.

Hibernate Validator validates container element constraints specified on the following standard Java containers:

  • implementations of java.util.Iterable (e.g. Lists, Sets),
  • implementations of java.util.Map, with support for keys and values,
  • java.util.Optional, java.util.OptionalInt, java.util.OptionalDouble, java.util.OptionalLong,
  • the various implementations of JavaFX’s javafx.beans.observable.ObservableValue.

It also supports container element constraints on custom container types (see Chapter 7, Value extraction ).

In versions prior to 6, a subset of container element constraints were supported. A @Valid annotation was required at the container level to enable them. This is not required anymore as of Hibernate Validator 6.

We present below a couple of examples illustrating container element constraints on various Java types.

In these examples, @ValidPart is a custom constraint allowed to be used in the TYPE_USE context.

2.1.3.1. With Iterable

When applying constraints on an Iterable type argument, Hibernate Validator will validate each element. Example 2.3, “Container element constraint on Set” shows an example of a Set with a container element constraint.