Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JSR 303 (Bean validation)?

I read many tutorials about JSR 303 spec, but I don't see any example ready for production. Everywhere described how to get Set<Constraintviolation<T>> object.

Example:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<Car>> violations = validator.validate(car);

But what next? I want to inform method caller (client) that method parameter is in inconsistent state.

What I must do with Set<ConstraintViolation<Car>>? I need manually iterate over Set<ConstraintViolation>, collecting all error messages into one string, and then throw an exception with this messages?

Or exist some more convenient ways out of the box?

Or it's better to provide validate method inside each bean?

like image 703
WelcomeTo Avatar asked Jan 28 '13 12:01

WelcomeTo


2 Answers

I would go with your first suggestion - iterate over the constraint violations. You don't necessarily create an error message that contains all that stuff. It is probably a good idea to just have an error message saying bean <bean> is not valid and set the constraint violations as a property on an exception.

Maybe you need to convert the constraint violations to another object, because otherwise you would make much of your application dependent on the bean validation api. That might be a too strong coupling.

Your problem is that it is very use case specific what to do with the constraint violations. There are many cases where you don't want to inform the caller about the constraint violations, but some other object. For example in a web form you want to inform your view model that it should also display these constraint violations. Throwing an exception is just another thing. Note that this won't be a ConstraintViolationException in most cases, but a application specific exception.

like image 168
SpaceTrucker Avatar answered Oct 20 '22 13:10

SpaceTrucker


It also depends on how you use Bean Validation. The use case you are describing is when you use the Bean Validation API directly yourself. In this case you will get a Set> as the result of the validate call. How you deal with it is up to you. However, a lot of technologies integrate Bean Validation and often hide all direct calls to the Bean Validation API. For example JPA. If you use JPA and Bean Validation is on the classpath, entities will be automatically validated on life cycle events (pre-persist/update/delete) and a javax.validation.ConstraintViolationException will be thrown in case of validation errors. Similar in JSF, there the validation of form element with Bean Validation happens automatically and the error can also be highlighted. So unless you want to use the plain Bean Validation API you will need to look for examples on how the technology of your choice integrates with JSR 303.

like image 44
Hardy Avatar answered Oct 20 '22 14:10

Hardy