diogocarmo
diogocarmo

Reputation: 970

@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?

Upvotes: 2

Views: 3132

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 208964

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.

Upvotes: 1

Franck
Franck

Reputation: 1764

Method Validations is only available starting in bean validation v 1.1 (e.g. hibernate validator 5.x impl) which is part of Java EE 7 only. On top of that to have it working without extra specific BV code your method must be part of a component which is integrated with bean validation (eg. CDI Beans, JAX-RS Resource). Your custom code works because you do not use method validation but rather BV constraints which are defined directly on your object.

Upvotes: 4

Related Questions