Monday, November 18, 2024
Google search engine
HomeLanguagesJavaSpring Boot – Validation using Hibernate Validator

Spring Boot – Validation using Hibernate Validator

Hibernate validators are very useful and they provide the following annotations that are very helpful for software development.

Annotation

Usages

@NotNull Char Sequence, Collection, Map, or Array object can be validated with this and they should not be null but can be empty
@NotEmpty Char Sequence, Collection, Map, or Array object can be validated with this and they should not be null and not empty
@NotBlank Char Sequence, Collection, Map, or Array objects can be validated with this and they should not be null and not empty and not blank
@Min Given Minimum value has to get satisfied
@Max Given Maximum value has to get satisfied
@Size Field size should be less than or greater than the specified field size
@Email Email can be validated with this
@Pattern Given RegEx Pattern has to be satisfied.

Let us go with a sample project that includes Hibernate validator.

Example Project

Project Structure:

Project structure

 

This is the maven project and hence the required dependencies need to be placed in pom.xml

Mandatory dependency for hibernate validator:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 <groupId>com.gfg.samplehibernatevalidator</groupId>
    <artifactId>springbootvalidationwithhibernatevalidator</artifactId>
    <version>v1</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
    <!-- Must for hibernate validator-->
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <!-- dependency for automatic reloads or live reload of applications -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>


Let us start with a bean class that can have the annotations

GeekEmployee.java

Java




import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
 
public class GeekEmployee {   
   
    @NotBlank(message = "Please enter proper employee name")
    @Size(min=5, message = "Name should be atleast 5 characters")
    @Size(max=12, message = "Name should not be greater than 12 characters")
    private String geekEmployeeName;
     
    @NotNull(message = "Please enter a valid salary")
    @Min(value=1000, message = "Salary must be atleast 1000.00")
    @Max(value=40000, message = "Salary should not be greater than 40000.00")
    private Double salary;
     
    @Email(message = "Please enter a valid email Id", regexp="^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,5}")
    @NotNull(message = "Please enter a valid email Id")
    private String geekEmailId;
     
    @NotBlank(message = "Please enter qualifications")
    @NotNull(message = "Please enter qualifications")
    private String qualifications;
 
    public String getQualifications() {
        return qualifications;
    }
 
    public void setQualifications(String qualifications) {
        this.qualifications = qualifications;
    }
 
    public String getGeekEmployeeName() {
        return geekEmployeeName;
    }
 
    public void setGeekEmployeeName(String geekEmployeeName) {
        this.geekEmployeeName = geekEmployeeName;
    }
 
    public Double getSalary() {
        return salary;
    }
 
    public void setSalary(Double salary) {
        this.salary = salary;
    }
 
    public String getGeekEmailId() {
        return geekEmailId;
    }
 
    public void setGeekEmailId(String geekEmailId) {
        this.geekEmailId = geekEmailId;
    }   
}


To collect all the errors, we need to have an “ExceptionHandler” and it is given below

ExceptionHandler.java

Java




import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
 
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler{
     
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception,
            HttpHeaders httpHeaders, HttpStatus httpStatus, WebRequest webRequest) {
        Map<String, Object> objectBody = new LinkedHashMap<>();
        objectBody.put("Current Timestamp", new Date());
        objectBody.put("Status", httpStatus.value());
  
        // Get all errors
        List<String> exceptionalErrors = exception.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.toList());
 
        objectBody.put("Errors", exceptionalErrors);
 
        return new ResponseEntity<>(objectBody, httpStatus);
    }
}


Let us try to save the geekemployees by accepting the inputs like “geekEmployeeName”,”salary”,”geekEmailId” and “qualifications”. We need a rest controller file to achieve the same.

GeekEmplooyeeController.java

Java




import javax.validation.Valid;
 
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class GeekEmplooyeeController {
     
    @PostMapping("/geekemployees")
    public ResponseEntity<GeekEmployee> saveEmployeeData (@Valid @RequestBody GeekEmployee geekEmployee) {
        return new ResponseEntity<GeekEmployee>(geekEmployee, HttpStatus.CREATED);
    }
}


Our last step is to write the main class that starts the spring boot project. Via eclipse also it can be started as an ordinary java application or since it is a maven application, it can be started as

mvn spring-boot:run

ValidationApplication.java

Java




import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ValidationApplication {
    public static void main(String[] args) {
        SpringApplication.run(ValidationApplication.class, args);
    }
}


On running the application, in the console, we can see as follows

 

Let’s check the working part by using the postman client as we are using post mapping

Output in Postman

 

Conclusion

By means of Hibernate validator, very easily front-end validations can be checked and that helps a lot in spring boot projects simply a dependency makes these kinds of validations to validate a page.

RELATED ARTICLES

Most Popular

Recent Comments