Sunday, 16 June 2019

Bean validation: JSR 380 (hibernate-validator)


In any application, validating data is a common task. Many times, we end up in writing same validation logic at many places (including presentation layer, Business layer, Data Access layer, service layer, persistence layer etc.,). To avoid these kinds of duplications, make the validations robust, JCP (Java Community Process) approves a JSR (Java Specification request) to validate beans.

Below table summarizes the bean validation JSRs approved by JCP. At the time of writing this article, JSR 380 is the latest specification approved by JCP.

JSR
Description
JSR 303
This JSR will define a meta-data model and API for JavaBeanTM validation based on annotations, with overrides and extended meta-data through the use of XML validation descriptors.
JSR 349
It is enhanced version of JSR 303
JSR 380
At the time of writing this article, It is the latest standard on bean validations. It leverages the language features in Java8. If you want to use JSR 380 features in your application, Java8 is the minimum requirement.

hibernate-validator API implements JSR 380 specification. In this tutorial series I am going to use below maven dependency.

 <dependencies>
  <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>6.0.10.Final</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
  <dependency>
   <groupId>javax.validation</groupId>
   <artifactId>validation-api</artifactId>
   <version>2.0.1.Final</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/javax.el/javax.el-api -->
  <dependency>
   <groupId>javax.el</groupId>
   <artifactId>javax.el-api</artifactId>
   <version>3.0.1-b04</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.glassfish.web/javax.el -->
  <dependency>
   <groupId>org.glassfish.web</groupId>
   <artifactId>javax.el</artifactId>
   <version>2.2.6</version>
  </dependency>

 </dependencies>

You are going to learn
      Setting up Environment for hibernate-validator
      Hibernate-validator: Hello World application
      Bean Validation: Built-in constraints
      AssertTrue: Validate trueness of the element
      @DecimalMax: Value must be <= this value
      DecimalMin: Value must be >= this value
      Digits: Number must be within accepted range
      Email: validate email
      Future: Element must represent a future instant, date or time

Previous                                                 Next                                                 Home

No comments:

Post a Comment