Showing posts with label hibernate validator. Show all posts
Showing posts with label hibernate validator. Show all posts

Sunday, 14 March 2021

Hibernate-validator: Hello World application

In this post, I am going to show you an example of bean validation API annotations @Min, @Size.

 

JSR 380 specification provides @Min, @Size annotation to validate the bean properties.

 

Below table summarizes these annotations.

 

Annotation

Description

@Min

If you annotate any number field with this annotation, then the element must be greater than or equal to the specified minimum value.

@Size

The annotated element size must be within given boundaries.

 

public class Employee {

	@Min(value=1)
	private int id;
	
	@Size(min=5, max=30)
	private String firstName;
	
	@Size(min=5, max=30)
	private String lastName;
	
	.....
	.....

}

 

For example,

 

@Min(value=1)

private int id;

I annotated id with @Min(value=1), this annotation make sure that the value of the id is >=1, else it generated validation error.

 

@Size(min=5, max=30)

private String firstName;

I annotated firstName with @Size(min=5, max=30), this annotation make sure that the length of the field firstName is minimum 5 character and maximum 30 character.

 

Find the below working application.

 

Employee.java

package com.sample.model;

import javax.validation.constraints.Min;
import javax.validation.constraints.Size;

public class Employee {

	@Min(value=1)
	private int id;
	
	@Size(min=5, max=30)
	private String firstName;
	
	@Size(min=5, max=30)
	private String lastName;
	
	public Employee(int id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

Test.java

package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.model.Employee;

public class Test {
	public static void main(String args[]) {
		ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
		Validator validator = validatorFactory.getValidator();

		Employee emp = new Employee(-1, "Hareesh", "Ram");

		Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

		for (ConstraintViolation<Employee> violation : validationErrors) {
			System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
		}
	}
}

When I ran above application, I seen below messages in the console.

id,must be greater than or equal to 1
lastName,size must be between 5 and 30

Since the fields id, firstName are violating the minimum requirements specified by using @Id, @Size annotations, validator generates these error messages.




 

Previous                                                    Next                                                    Home

Setting up Environment for hibernate-validator

I am going to use Hibernate validator '6.0.10.Final'.

		<!-- 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>

 

Since Hibernate validator requires an implementation of Unified Expression Language (JSR 341) specification. If you are using Hibernate-validator in standalone servlet container such as tomcat, jboss then these dependencies are already provided. But if you are using Hibernate-validator in standalone application, then you need to provide below JSR 341 dependencies manually.

		<!-- 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>

My pom.xml looks like below.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>hibernateValidator</groupId>
	<artifactId>hibernateValidator</artifactId>
	<version>1</version>

	<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>
</project>




 

 

 

Previous                                                    Next                                                    Home

Thursday, 11 March 2021

Java 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>

 

 

 

Previous                                                    Next                                                    Home

Sunday, 16 June 2019

Hibernate-validator: Hello World application


In this post, I am going to show you an example of bean validation API annotations @Min, @Size.

JSR 380 specification provides @Min, @Size annotation to validate the bean properties.

Below table summarizes these annotations.

Annotation
Description
@Min
If you annotate any number field with this annotation, then the element must be greater than or equal to the specified minimum value.
@Size
The annotated element size must be within given boundaries.

public class Employee {

 @Min(value=1)
 private int id;
 
 @Size(min=5, max=30)
 private String firstName;
 
 @Size(min=5, max=30)
 private String lastName;
 
 .....
 .....

}

For example,

@Min(value=1)
private int id;
I annotated id with @Min(value=1), this annotation make sure that the value of the id is >=1, else it generated validation error.

@Size(min=5, max=30)
private String firstName;
I annotated firstName with @Size(min=5, max=30), this annotation make sure that the length of the field firstName is minimum 5 character and maximum 30 character.

Find the below working application.

Employee.java
package com.sample.model;

import javax.validation.constraints.Min;
import javax.validation.constraints.Size;

public class Employee {

 @Min(value=1)
 private int id;
 
 @Size(min=5, max=30)
 private String firstName;
 
 @Size(min=5, max=30)
 private String lastName;
 
 public Employee(int id, String firstName, String lastName) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}


Test.java
package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
  Validator validator = validatorFactory.getValidator();

  Employee emp = new Employee(-1, "Hareesh", "Ram");

  Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

  for (ConstraintViolation<Employee> violation : validationErrors) {
   System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
  }
 }
}

When I ran above application, I seen below messages in the console.

id,must be greater than or equal to 1
lastName,size must be between 5 and 30


Since the fields id, firstName are violating the minimum requirements specified by using @Id, @Size annotations, validator generates these error messages.



Previous                                                 Next                                                 Home