Melih
Melih

Reputation: 775

Alternative Annotations to Java Bean Validation Without Using Hibernate

I am working on a project that I need to put some limitations/constrains on the fields of the models(e.g. "String name" field should not exceed 10 characters) . I can only find Java Bean Validation API for this job. However as I see, it is used with Hibernate and Spring Framework.

Unfortunately, an ORM like Hibernate was not used in the project. We are using DAO pattern and JDBI for database operations.

Is there any alternative annotations on Java which helps to put constrains on the fields like Bean Validation does( and hopefully works with magic like Lombok does)? I need basically Size, Min/Max and NonNull annotations.

Basically something like this:

class User {

  @Size(max = 10)
  String name;
}

Upvotes: 4

Views: 9893

Answers (2)

Mizuki
Mizuki

Reputation: 2233

karelss already answered, you can also use javax.validation.constraints package here maven link. Here is possible implementation and test code (not perfect one).

User.java

  import javax.validation.constraints.Size;

        class User {

            @Size(max = 10)
            String name;

            public String getName() {
            return name;
            }

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

        }

UserTest.java

import static org.junit.Assert.assertEquals;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.Test;

public class UserTest {

    @Test
    public void test() {
    User user = new User();
    // set name over 10
    user.setName("12345678912");

    // validate the input
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    for (ConstraintViolation v : violations) {
        String key = "";
        if (v.getPropertyPath() != null) {
        key = v.getPropertyPath().toString();
        assertEquals("name", key);
        assertEquals("size must be between 0 and 10", v.getMessage());
        }

    }
    assertEquals(1, violations.size());
    }

}

Upvotes: 6

Javier Toja
Javier Toja

Reputation: 1762

Java Bean Validation API is the right tool for this job, but as you say is an api, if you are using an application server, you will have different implementations and you can use whatever you want, it's not linked to hibernate or spring, what you see are different providers of the api implementatión. This api works with objects, you can annotate any object with it.

If you don't want to include dependencies you can implement this validations in a compatible way using your own annotations like here

Java 7 Bean validation API

Upvotes: 5

Related Questions