@Digits Javax Validation Hibernate Spring Boot Example

@Digits Javax Validation Hibernate Spring Boot Example

In this post, we will see @Digits Javax Validation Hibernate Spring Boot Example Using Oracle Database. We will see how to use @Digits annotation with the BigDecimal type filed, also we will define an error handler for the validation error message.

  • @Digits annotation has been defined in javax.validation.constraints package and the field where we are going to use this annotation must be a number.
  • We need to use mandatory attributes integer and fraction with @Digits. For example @Digits(integer = 5, fraction = 2).
  • This annotation support following types – BigDecimal, BigInteger, CharSequence, int, long, byte, short, Integer, Long, Byte and Short.

Student.java

@Entity
public class Student {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private int id;

   @Column(name = "student_name")
   private String studentName;

   @Column(name = "fee")
   @Digits(integer = 4, fraction = 2)
   private BigDecimal fee;

}

Valid Request Data –

@Digits Javax Validation Hibernate

Invalid request data –

@Digits Javax Validation

@Digits Javax Validation Hibernate Spring Boot Example from scratch.

After running below example, we will be able to save an entity in the database if we have valid request data else it will show the validation error message.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details as below and click on finish.

Hibernate Validator Spring Boot

Modify pom.xml

<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>hibernatevalidatorexample</groupId>
	<artifactId>hibernatevalidatorexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>hibernatevalidatorexample</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

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

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Directory structure –


Hibernate Validator Example

Student.java

package com.entity;

import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Digits;

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "student_name")
	private String studentName;

	@Column(name = "fee")
	@Digits(integer = 4, fraction = 2)
	private BigDecimal fee;

	public int getId() {
		return id;
	}

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

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public BigDecimal getFee() {
		return fee;
	}

	public void setFee(BigDecimal fee) {
		this.fee = fee;
	}

}

StudentController.java

package com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.entity.Student;
import com.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Student saveBook(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.saveStudent(student);
		return studentResponse;
	}

}

StudentRepository.java – interface

package com.repository;

import java.io.Serializable;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.entity.Student;
@Repository
public interface StudentRepository extends CrudRepository<Student,Serializable> {
	
}

StudentService.java – interface

package com.service;

import org.springframework.stereotype.Component;

import com.entity.Student;

@Component
public interface StudentService {
	public Student saveStudent(Student student);
}

StudentServiceImpl.java


package com.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.entity.Student;
import com.repository.StudentRepository;
import com.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Override
	public Student saveStudent(Student student) {

		validateEntity(student);
		Student studentresponse = studentRepository.save(student);
		return studentresponse;
	}

	private void validateEntity(Student student) {
		List<String> errorMessage = new ArrayList<>();
		Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

		Set<ConstraintViolation<Student>> constraintViolations = validator.validate(student);

		for (ConstraintViolation<Student> constraintViolation : constraintViolations) {
			errorMessage.add(constraintViolation.getMessage());
		}

		if (errorMessage.size() > 0) {
			throw new ConstraintViolationException(constraintViolations);
		}

	}

}

GlobalErrorHandler.java – Let’s define a error handler class. This class will be used when validateEntity() method will throw ConstraintViolationException(See more details about GlobalErrorHandler here).

package com.controller;

import java.util.List;
import java.util.ArrayList;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.entity.ResponseError;

@ControllerAdvice
public class GlobalErrorHandler {
	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseBody
	public ResponseError handleCustomException(ConstraintViolationException ex) {
		ResponseError responseError = new ResponseError();
		List<String> errorMessages = new ArrayList();
		for (ConstraintViolation constraintViolation : ex.getConstraintViolations()) {
			errorMessages.add(constraintViolation.getPropertyPath() + " : " + constraintViolation.getMessage());
		}
		responseError.setErrorMessage(errorMessages);
		responseError.setStatusCode(HttpStatus.BAD_REQUEST.value());
		return responseError;

	}
}

ResponseError.java

package com.entity;

import java.util.List;

public class ResponseError {
	private List<String> errorMessage;
	private int statusCode;

	public List<String> getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(List<String> errorMessage) {
		this.errorMessage = errorMessage;
	}

	public int getStatusCode() {
		return statusCode;
	}

	public void setStatusCode(int statusCode) {
		this.statusCode = statusCode;
	}

}

SpringMain.java

package com.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.*")
@EntityScan("com.entity")
public class SpringMain {
	public static void main(String[] args) {

		SpringApplication.run(SpringMain.class, args);
	}

}

JpaConfig.java

package com.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.repository")
public class JpaConfig {

}

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

Let’s run the SpringMain class(run as java application).

Valid request

{
"studentName":"rakesh",
"fee":1244
}

response 
{
    "id": 3,
    "studentName": "rakesh",
    "fee": 1244
}


----------------------------
Invalid Request

{
"studentName":"rakesh",
"fee":12445.8999
}

Response

{
    "errorMessage": [
        "fee : numeric value out of bounds (<4 digits>.<2 digits> expected)"
    ],
    "statusCode": 400
}

That’s all about @Digits Javax Validation Hibernate Spring Boot Example.


You may like.

See Docs.