Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct a ConstraintViolationException in Bean Validation 1.0?

Tags:

I am puzzled by the javax.validation API. I am writing a simple test to understand it:

Sample sample = new Sample();
Set<ConstraintViolation<Sample>> violations = validator.validate(sample);
if (!violations.isEmpty()) {
    // Eclipse refuses to let me use my violations variable
    throw new ConstraintViolationException(violations);
}

How should I declare the set of violations so I can use it in my exception constructor?

like image 343
Raylite3 Avatar asked Aug 23 '12 17:08

Raylite3


People also ask

What are bean validation features?

The Bean Validation 2.0 specification provides an annotation based model for validating JavaBeans. It can be used to assert and maintain the integrity of data as it travels through an application. This feature is built on top of the Hibernate Validator Engine.

How does Java Bean validation work?

The Bean Validation API is a Java specification which is used to apply constraints on object model via annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can also provide custom validations. As Bean Validation API is just a specification, it requires an implementation.

What is JPA Validator?

Data validation is a common task that occurs in all layers of an application, including persistence. The Java™ Persistence API (JPA) 2.0 provides support for the Bean Validation API so that data validation can be done at run time.


2 Answers

You can work around this like so:

throw new ConstraintViolationException(
    new HashSet<ConstraintViolation<?>>(violations));

You may be interested in tracking BVAL-198 which addresses this issue.

like image 58
Gunnar Avatar answered Sep 29 '22 12:09

Gunnar


This is a known usability issue in Bean Validation 1.0. This issue was addressed in Bean Validation 1.1 by issue BVAL-198, "Simplify creation of ConstraintViolationExceptions". Upgrading to Bean Validation 1.1 or later will allow your code to compile as written.

The specific issue is that the ConstraintViolationException constructors accepted Set<ConstraintViolation<?>> for their constraintViolations parameter. Since Set<ConstraintViolation<Sample>> is not a subtype of Set<ConstraintViolation<?>>, it could not be passed into the constructor, with a compilation error occurring when attempting to do so.

Bean validation 1.1.0 changed the constructors to instead accept Set<? extends ConstraintViolation<?>>. As this is a supertype of Set<ConstraintViolation<Sample>>, it can be passed directly to the constructor.

As mentioned in this other answer, the fix while still on Bean Validation 1.0 was to pass in a Set<ConstraintViolation<?>> instead of Set<ConstraintViolation<Sample>>:

throw new ConstraintViolationException(
    new HashSet<ConstraintViolation<?>>(violations));
like image 24
M. Justin Avatar answered Sep 29 '22 14:09

M. Justin