3

The question I am asking could be really simple(even foolish).

I was using validation in spring-hibernate MVC app. I am using constraints such as @NotNull, @Pattern which come from javax.validation packages. When I us constraints such as @Email it is imported from org.hibernate.validator.constraints. In the validator class I use ValidatorFactory and other classes or interfaces(such as Validation, Validator) all of which are from javax.validation. I got really confused with this.

Then I started going deeper into what exactly javax validator and hibernate validator packages are, and apparently they are implementations of JSR303.

To validate, I use

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

To further confuse me, I read one more way of instantiating ValidatorFactory which goes like this -

ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure().buildValidatorFactory();

and it works fine!

Please help me understand both of these better.

Thanks for help.

nikhil
  • 45
  • 1
  • 5
  • Thanks. So you mean they are the same? if they are, Why are there so many implementations of the same thing? Like, there should be some difference, right? – nikhil Sep 22 '17 at 07:34
  • No, I'm not saying they are the same. I'm saying that one defines the standard, and has no impementation, and that the other provides an implementation of that standard. There aren't many implementations of bean validation. But there can be several ones, each being more or less efficient, and provide more or less additional features (like the email validator) over what is required by the standard. – JB Nizet Sep 22 '17 at 07:36
  • So, in the imports when I see import javax.validation.constraints, do you mean it is implemented internally by Hibernate but the name is javax.validation for the sake of standard? – nikhil Sep 22 '17 at 07:45
  • Apparently, javax.validation is provided by Oracle and hibernate validator is just another implementation of JSR 303. – nikhil Sep 22 '17 at 08:24

1 Answers1

2

As a whole lot of things in Java (security, JDBC, JPA, etc. etc.), there is a standard, call bean validation, that defines interfaces and standard classes (i.e. javax.validation classes), and you can choose between several implementations of these classes and interfaces (hibernate validator being one of them).

The landing page of hibernate validator tells it:

Hibernate Validator 5.x is the reference implementation Bean Validation 1.1!

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks. So you mean they are the same? if they are, Why are there so many implementations of the same thing? Like, there should be some difference, right? – nikhil Sep 22 '17 at 07:35