Hibernate Validation

In this tutorial we will describe how to validate you application in hibernate.

Hibernate Validation

Hibernate Validation

In this tutorial we will describe how to validate you application in hibernate.

Hibernate Validation  : Validation is the concept to check whether your data is valid or not. Data validation is very common and important process for any application.
Validation is required in presentation layer as well as persistent layer. It is wastage of time to apply validation in each layer.
Hibernate provides very strong annotations validation source. It works directly with your domain model. It reduces overhead of applying validation in each layer.

You can use constraint its java annotation for validation. Now we are going to describe how to annotate an object with these annotation.

Example:  In this example we are using most of validation constraint to validate name, roll, email.

@NotEmpty- checks the element not be empty. It is defined in org.hibernate.validator.constraints.NotEmpty class .

@NotNull - Checks the element not null. It is defined in javax.validation.constraints.NotNull class.

@Max(N) - checks the max length not exceed to 'N'. It is defined in javax.validation.constraints.Max class.

@Min(N) -checks the length not less than 'N'.  It is defined in javax.validation.constraints.Min class.

@Email- Checks the inputted element is in valid email format.  It is defined in javax.validation.constraints.Email class.

package net.roseindia.student;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

public class Student {

@NotEmpty(message = "Please Specify Name")
private String name;

@NotNull
@Max(110)
@Min(1)
private Integer roll;
private String gender;
private String country;
private String community;

@Email(message = "Enter valid email id")
private String email;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getRoll() {
return roll;
}

public void setRoll(Integer roll) {
this.roll = roll;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public String getCommunity() {
return community;
}

public void setCommunity(String community) {
this.community = community;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

}

Output:

Click here to download complete source code