Java Validation

By using EJB, validation can be processed automatically. However, this article talks about how to do it manually. I separate the whole procedure into 3 steps: Entity Bean Annotation, Processing Validation, and Unit Testing.

Entity Bean Annotation

You can tell how you want the fields of your entity beans to be validated by putting annotations on them.

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name = "student")
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Size(min = 2, max = 25)
    private String name;

    // getters and setters...
}

The Bold Annotations are going to be used for validating the value of name field.

Processing Validation

In your functional class, such as a Service class, you can use Validator to validate the entity bean. It will process validation for the entire instance of the Entity and return all ConstraintViolations in a Set. In order to get all the elements of the Set, you need an Iterator.

import java.util.Iterator;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

public class StudentServices {

    Validator validator; // the instance of validator is usually being injected, or passed in

    public void validate(Student student){
        Iterator<ConstraintViolation<Student>> errors = validator.validate(student).iterator();
        if (errors.hasNext()) {
            ConstraintViolation<Student> violation = errors.next();
            throw new RuntimeException(violation.getPropertyPath().toString() + ": " + violation.getMessage()); // property path is the field name of the entity where the value violates the constrain
        }
    }
}

Validator can validate an instance of the Entity by using its (entity’s) constraint.

Unit Testing

This unit test shows how Validator being created, and if all have been done correctly, the test should pass.

import static org.junit.Assert.*;

import javax.validation.Validation;
import javax.validation.Validator;

import org.junit.Before;
import org.junit.Test;

public class StudentServicesTest {

    private StudentServices studentServices;

    @Before
    public void initTestCase() {
        studentServices = new StudentServices();
        studentServices.validator = Validation.buildDefaultValidatorFactory().getValidator(); // This is how a Validator being created
    }

    @Test(expected = RuntimeExeption.class)
    public void validate() {
        studentServices.validate(new Student()); // this instance of Student entity does not have a name (name field is null), which violates the @NotNull annotation on name field
    }
}

The message of thrown RuntimeExeption will be something like “name: …” because the property path was added when it’s been throwing out.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s