Search code examples
javahibernatejerseybean-validationjersey-2.0

@Valid not throwing exception


I'm trying to validate my JPA Entity with @Valid like this:

public static void persist(@Valid Object o)

It worked fine for a while but now it stopped working and I'm not sure why. I tried to do it manually inside the persist method, and it works as expected:

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<Object>> constraintViolations = validator.validate(o);

    if (!constraintViolations.isEmpty()) {
        throw new ConstraintViolationException(constraintViolations);
    }

What could be happening or how can I debug this?


Solution

  • Won't work on arbitrary services. In Jersey it will only work for resource methods. So validate the incoming DTO in your resource method.

    @POST
    public Response post(@Valid SomeDTO dto) {}
    

    See more at Bean Validation Support


    UPDATE

    So to answer the OP's comment about how we can make it work on arbitrary services, I created a small project that you can plug and play into your application.

    You can find it on GitHub (jersey-hk2-validate).

    Please look at the tests in the project. You will find a complete JPA example in there also.

    Usage

    Clone, build, and add it your Maven project

    public interface ServiceContract {
        void save(Model model);
    }
    
    public class ServiceContractImpl implements ServiceContract, Validatable {
        @Override
        public void save(@Valid Model model) {}
    }
    

    Then use the ValidationFeature to bind the service

    ValidationFeature feature = new ValidationFeature.Builder()
            .addSingletonClass(ServiceContractImpl.class, ServiceContract.class).build();
    ResourceConfig config = new ResourceConfig();
    config.register(feature);
    

    The key point is to make your service implementation implement Validatable.

    The details of the implementation are in the README. But the gist of it is that it makes use of HK2 AOP. So your services will need to be managed by HK2 for it to work. That is what the ValidationFeature does for you.