Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 688
Melih Avatar asked Sep 14 '25 09:09

Melih


1 Answers

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());
    }

}
like image 111
Byaku Avatar answered Sep 16 '25 00:09

Byaku