Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java Bean Validation example

farenda 2017-01-17 0

In this post we show Java Bean Validation example! Bean Validation is fantastic and flexible library that can be used in JEE and JSE programs to verify data!

Bean Validation implementation

Because Bean Validation is only an API we need to add an actual implementation to our project (assuming we’re running a project in JSE, without any JEE server). As the implementation we’ll use Hibernate Validator – the reference implementation. Let’s add project dependencies to pom.xml:

<!-- this will provide also Bean Validator API: -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>
<!-- Needed by HV to substitute prams in messages: -->
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>javax.el</artifactId>
    <version>2.2.4</version>
    <scope>runtime</scope>
</dependency>

Business object to validate

To illustrate how to validate data using Bean Validator let’s create a very simple class with a few constraints:

package com.farenda.javax.validation;

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

public class Player {

    // name have to be 3 chars:
    @Size(min = 3, max = 3)
    private String name;

    // possible score in game:
    @Min(0) @Max(1000)
    private int score;

    public Player(String name, int score) {
        this.name = name;
        this.score = score;
    }

    // just for logs
    @Override
    public String toString() {
        return "Player{name='" + name + '\'' + ", score=" + score + '}';
    }
}

Bean validator

Instantiating validator

The first thing we have to do is to create ValidationFactory that will provide us an implementation of Validator. Then we can use it to perform validations of our beans and finally close the ValidatorFactory, which will close the factory and all it’s validators:

package com.farenda.javax.validation;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class RunValidator {

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

        validate(validator, new Player("ABC", 44));

        validate(validator, new Player("a", 0));

        vf.close();
    }

    private static void validate(Validator validator, Player player) {
        // see below...
    }
}

Note: Implementations of ValidationFactory and Validator are thread-safe.

Bean Validation method

Having a Validator instance we can perform actual validation of the Player. The task is very simple – we just call validator.validate(player). This method returns non-null set of validation errors (NullObject Pattern). If it is empty then we know that the object is valid, else we can get details of each violated constraint and can throw ConstraintViolationException with the violations as the only argument:

private static void validate(Validator validator, Player player) {
    Set<ConstraintViolation<Player>> violations
        = validator.validate(player);
    if (violations.isEmpty()) {
        System.out.println("Valid player: " + player);
    } else {
        for (ConstraintViolation<Player> violation : violations) {
            System.out.println("Invalid player: "
                 + violation.getRootBean());
            System.out.println("Offending property: "
                 + violation.getPropertyPath());
            System.out.println("Offending value: "
                 + violation.getInvalidValue());
            System.out.println("Message: "
                 + violation.getMessage());
        }
        throw new ConstraintViolationException(violations);
    }
}

Results of validation

Here’s the output of running Bean Validation in the above program:

sty 17, 2017 10:40:39 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.2.4.Final
Valid player: Player{name='ABC', score=44}
Invalid player: Player{name='a', score=-1}
Offending property: name
Offending value: a
Message: size must be between 3 and 3
Invalid player: Player{name='a', score=-1}
Offending property: score
Offending value: -1
Message: must be greater than or equal to 0
Exception in thread "main" javax.validation.ConstraintViolationException
        at com.farenda.javax.validation.RunValidator.validate(RunValidator.java:30)
        at com.farenda.javax.validation.RunValidator.main(RunValidator.java:14)

As you can see all constraints were checked and collected – the second player violated name and score constraints.

References:

  • Bean Validation specification
Share with the World!
Categories Java Tags bean-validation, java
Previous: java.lang.InterruptedException
Next: Bean Validation Unit Testing

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok