Hibernate validator example LEARNOVITA

Hibernate Validator Tutorial | Learn in 1 Day FREE

Last updated on 10th Aug 2022, Blog, Tutorials

About author

Yeshwant singh (Java Developer )

Yeshwant Singh is a Java developer and contributes in-depth articles on various big data technologies. He also has experience in Hadoop, microservices, Commvault, and a few BI tools.

(5.0) | 19675 Ratings 2229

Hibernate Validator

Hibernate Bean Validation Learn to use hibernate validator to validate the sector values during a Java bean. Bean validation API offers some terribly helpful annotations which will be applied to any bean property for the aim of maintaining information integrity. Bean validation in Java is supported via JSR-303 (Bean Validation one.0), JSR-349 (Bean Validation one.1), and JSR 380 (Bean Validation two.0).

    1. 1. Dependencies
    2. 2. obtaining Started with Bean Validation
    3. 2.1. Annotate Model with JSR-380 Annotations
    4. 2.2. Default Resource Bundle
    5. 2.3. death penalty the Validations
    6. 3. Applying Constraints
    7. 4. Bootstrapping Validation Factory
    8. 5. Custom Resource Bundles
    9. 6. Runtime Message Interpolation
    10. 6.1. Parameters Resolution
    11. 6.2. Demo
    12. 7. Bean Validation Annotations List
    13. 7.1. Default Annotations
    14. 7.2. Hibernate Validator Specific Annotations
    15. 8. Conclusion
Hibernate Validator

1. Dependencies:

Start with adding the newest version of the hibernate-validator module. This transitively pulls within the dependency to the Djakarta Bean Validation API (Jakarta. validation: Jakarta. Validation API).Older versions had a dependency on java. validation: validation-API. If we would like to use java. validation. Validation Factory in Hibernate vi or later versions, we are able to specify the Djakarta. persistence. Validation. factory property and set it’s worth java vax. validation. Validation Factory.

  • org. hibernate. validator
  • hibernate-validator

7.0.4. Final

Bean validation permits expressions within the error messages. To dissect these expressions, we tend should add a dependency on each expression language API and implementation of that API. the newest The version of the validator needs AN implementation of Djakarta Expression Language.

4.0.1

We can in addition embrace Hibernate Validator Annotation Processor helps in preventing mistakes by plugging into the build method and raising compilation errors whenever constraint annotations are incorrectly used.

  • org. hibernate. validator
  • hibernate-validator-annotation-processor

7.0.4. Final

Finally, if we tend to don’t seems to be running the application within a Djakarta engineering application server, so we should always add the hibernate-validator-CDI dependency. This provides CDI- managed beans for Validator and Validator Factory and allows dependency injection in constraint validators yet as custom message interpolators, travelable resolvers, constraint validator factories, parameter name suppliers, clock suppliers, and worth extractors.

2. obtaining Started with Bean Validation

Let’s quickly run a demo program to possess a basic understanding before deep diving into details.

2.1. Annotate Model with JSR-380 Annotations Start with applying the validation constraints within the fields of a model category. we tend to victimize the User category and apply constraints to id, name, and email fields.

package com. How to do it in java. example. model;

  • import java. validation. constraints. Email;
  • import java. validation. constraints. Not Empty;
  • import java. validation. constraints. Not Null;
  • import java. validation. constraints. Size;
  • public category User
  • {private| personal| non-public “>personal Long id;
  • @Size (max = twenty, min = 3, message = “”)
  • @Not Empty (message = “Please enter name “)
  • non-public String name;
  • @Email (message = “”)
  • @Not Empty (message = “Please enter email “)
  • non-public String email;
  • //Setters and Getters
  • }

2.2. Default Resource Bundle

By default, all messages are resolved from Validation Messages. properties come in the class path. If the file doesn’t exist, the message resolution doesn’t happen.

  • Validation Messages. properties
  • user. name. invalid =Invalid Username
  • user. Email. invalid =Invalid Email

2.3. death penalty the Validations

Now let’s execute the bean validation on the User instance.

  • public category Test Hibernate Validator
  • that returns validator
  • Validator Factory mill = Validation. Build Default Validator Factory ();
  • //It validates bean instances
  • Validator validator= mill. Get Validator ();
  • User user= new User (null, “1”, “abcgmail.com”);
  • //Validate bean
  • Set constraint Violations = validator. Validate (user);
  • //Show errors
  • if (constraint violations. Size () > 0)
  • } else
  • “>
  • }
  • }

Program output:

  • Please enter id
  • Invalid Email
  • Invalid Username

3. Applying Constraints

Annotation constraints are applied over four places during a class:

field constraints,property constraints container component constraintsclass constraints Obviously, not all constraints are placed on all of those levels.

  • //Class level constraint
  • @Valid User Demographics
  • public category User {
  • //Field level constraint
  • @Not Null
  • non-public String name;
  • //Property level constraint
  • @Not Null
  • public String get email () come back email;
  • }
  • //other fields and accessors
  • }

4. Bootstrapping Validation Factory

We can get a Validator by retrieving a Validator Factory via one of the static ways on Djakarta. validation.

  • Validation and occupation get Validator () on the mill instance.
  • ValidatorFactory validator factory = Validation. build Default Validator Factory ();
  • Validator validator= validator factory. Get Validator ();
  • In case there are multiple validation suppliers within the runtime, we are able to get a selected validator by its name.
  • ValidatorFactory validator Factory = Validation. By Provider (Hibernate Validator. class)
  • .configure ().build Validator Factory();
  • Validator validator= validator Factory. Get Validator ();
  • If the application supports CDI, it’s terribly straightforward to retrieve Validator Factory and Validator
  • instances with @Jakarta inject. Inject. In case, the application is running within a Djakarta engineering
  • server, we are able to use @Resource annotation yet.
  • @Inject
  • private ValidatorFactory validator factory;
  • @Inject
  • private Validator;
  • In the case of multiple suppliers, use @Hibernate Validator to set up the particular validator.
  • @Inject
  • @Hibernate Validator
  • private ValidatorFactory validator factory;
  • @Inject
  • @Hibernate Validator
  • private Validator;

5. Custom Resource Bundles

By default, the framework picks up validation messages from Validation Messages. properties come in the Classpath we tend to might set up the custom property files as below.

For example, place these 2 property files in the classpath:

messages. properties

other messages. properties

  • Add each property file to Resource Bundle Message Interpolator.
  • Validator validate action. By default Provider ()
  • .configure ()
  • .message Interpolator (
  • new Resource Bundle Message Interpolator (
  • new Aggregate Resource Bundle Locator
  • (Arrays. as List “messages “, “Other Messages”
  • )
  • )
  • )
  • )
  • .build Validator Factory().get Validator ();

6. Runtime Message Interpolation

Message interpolation is that the method of making error messages for profaned Bean Validation constraints.

6.1. Parameters Resolution

During message resolution, we are able to use runtime values to form validation messages with additional significance. This parameter price resolution in messages happens in 2 ways:

To resolve values in annotation attributes, merely enclose them with curled braces. E.g. or. To resolve the field’s runtime price, use placeholder $.

6.2. Demo

Start with making a message resource file with placeholders.

  • Validation messages. properties
  • user. name. invalid=’$’ is AN invalid name. It should be minimum chars and most.
  • Now annotate the sphere within the Bean category.
  • @Size (max = twenty, min = 3, message = “”)
  • private String name;
  • Now run the validator and observe the output.
  • User = new User (23l, “x y”, “abc@gmail.com”);
  • Set constraint violations = validator. Validate (user);
  • Output
  • ‘x y ‘ is AN invalid name. It should be a minimum of three chars and twenty chars.

7. Bean Validation Annotations List

Now once we shrewdly use hibernate validator in an exceedingly programmatic manner. Let’s undergo all the annotations that we are able to use in bean categories.

7.1. Default Annotations

Default Annotations

Annotation Description

  • @Assert False Checks that the annotated part is fake
  • @Assert True Checks that the annotated part is true
  • @Decimal Max (value=, inclusive=) Checks whether or not the annotated price is a smaller amount
  • than the required most Big Decimal price, once inclusive=false. Otherwise, whether or not the worth is a
  • smaller amount than or adequate the required most.
  • @Decimal Min (value=, inclusive=) Checks whether or not the annotated price is larger than the
  • required minimum Big Decimal price.
  • @Digits (integer=, fraction=) Checks whether or not the annotated price could be a variety having up
  • to number digits and fraction aliquot digits.
  • @Email Checks whether or not the required character sequence could be a valid email address.
  • @Max(value=) Checks whether or not the annotated price is a smaller amount than or adequate the
  • required most.
  • @Min(value=) Checks whether or not the annotated price is over or adequate to the required
  • minimum
  • @Not Blank Checks that the annotated character sequence isn’t null and also the cut length is bigger
  • than zero.
  • @Not Empty Checks whether or not the annotated part isn’t null or empty.
  • @Null Checks that the annotated price is null
  • @Not Null Checks that the annotated price isn’t null
  • @Pattern (regex=, flags=) Checks if the annotated string matches the regular expression regex
  • considering the given flag match
  • @Size (min=, gamma hydroxybutyrate=) Checks if the annotated element’s size is between min and max
  • (inclusive)
  • @Positive Checks if the part is strictly positive. Zero values are thought about as invalid
  • @Positive or Zero Checks if the part is positive or zero.
  • @Negative Checks if the part is strictly negative. Zero values are thought about invalid.
  • @Negative or Zero Checks if the part is negative or zero.
  • @Future Checks whether or not the annotated date is within the future.
  • @Future or Present Checks whether or not the annotated date is within the gift or within the future.
  • @Past Checks whether or not the annotated date is within the past
  • @Past or Present Check whether or not the annotated date is within the past or within the gift.

7.2. Hibernate Validator Specific Annotations

In addition to the constraints outlined by the Bean Validation API, Hibernate Validator provides many helpful custom constraints that are listed below.

Annotation Description

Annotation Description
  • @Credit Card Number (ignore Non-Digit Characters=) Checks that the annotated character sequence
  • passes the Luhn confirmation. Take a look at it. Note, that this validation aims to examine for user
  • mistakes, not MasterCard validity!
  • @Currency(value=) Checks the currency unit of the annotated java. money. The monetary
  • Amount is an element of the required currency units.
  • @Duration Max (days=, hours=, minutes=, seconds=, Millis=, nanos=, inclusive=) Checks that annotated
  • java. Time. The duration part isn’t bigger than the required price within the annotation.
  • @Duration Min (days=, hours=, minutes=, seconds=, Millis =, nanos=, inclusive=) Checks that annotated
  • java. Time. The duration part isn’t but the required price within the annotation.
  • @EAN Checks that the annotated character sequence could be a valid EAN barcode. The default is EAN- 13.
  • @ISBN Checks that the annotated character sequence could be a valid ISBN.
  • @Length (min=, gamma hydroxybutyrate=) Validates that the annotated character sequence is between min and max enclosed.
  • @Range (min=, max=) Checks whether or not the annotated price lies between (inclusive) the required minimum and most.
  • @Unique Elements Checks that the annotated assortment solely contains distinctive parts.
  • @URL Checks if the annotated character sequence could be a valid address in line with RFC2396.
  • @Code Point Length (min=, max=, normalization Strategy=) Validates that the code purpose length of the annotated character sequence is between min and gamma-hydroxybutyrate enclosed.
  • @Luhn Check (start Index=, end Index=, check Digit Index=, ignore Non-Digit Characters=) Checks that the digits among the annotated character sequence pass the confirmation algorithmic program.
  • @Normalized(form=) Validates that the annotated character sequence is normalized in line with the given kind.
  • @Mod10Check (multiplier=, weight=, start Index =, end Index=, check Digit Index=, ignore Non-Digit Characters=) Checks that the digits among the annotated character sequence pass the generic mod ten confirmation algorithmic program.
  • @Mod11Check Checks that the digits among the annotated character sequence pass the mod eleven confirmation algorithmic program.
  • @Script Assert (lang =, script=, alias=, report On=) Checks whether or not the given script will with success be evaluated against the annotated part. A JSR 223 implementation should be a gift within the classpath.

8. Conclusion

In this hibernate tutorial, we have a tendency to learn to use the bean validation constraints in an exceedingly straightforward POJO category. we have a tendency to additionally learn to inject the bean Validator interface to validate the POJO against the applied constraints. We additionally learned to customize the resource bundle and message interpolation. Finally, we have a tendency to went through the entire list of bean validation constraints provided by Djakarta persistence API and Hibernate-provided custom constraints.

Are you looking training with Right Jobs?

Contact Us

Popular Courses