Migrating from Hibernate Validator
This guide is for a project that validates with Hibernate Validator today and wants to run on rulii-bean-validation. The beans do not change. What changes is one dependency, a few configuration calls, and the handful of Hibernate-specific features that have a different shape here or no equivalent. Each section says which.
Checklist
Section titled “Checklist”- Replace
org.hibernate.validator:hibernate-validatorwithorg.rulii:rulii-bean-validation. Keep your EL implementation if messages use${...}. - Make sure Hibernate Validator is really gone from the classpath, Spring Boot’s validation starter included. With rulii-spring 2.3 this step is optional: add this library beside it and the application’s
Validatoris rulii’s even with Hibernate Validator still present. - Replace
Validation.byProvider(HibernateValidator.class)withRuliiValidationProvider.class, andHibernateValidatorConfigurationcalls with theirRuliiConfigurationcounterparts from the table below. - Change imports of
org.hibernate.validator.constraints.*toorg.rulii.validation.beans.constraints.*for the constraints that exist here, and replace the ones that do not. - In custom validators, replace
HibernateConstraintValidatorContextwithRuliiConstraintValidatorContext. - Replace
@GroupSequenceProvider,@ScriptAssertand@ParameterScriptAssertas described below. - Run your tests. Violations, paths and messages are meant to come out the same; the specification coverage page lists the known differences.
1. The Dependency
Section titled “1. The Dependency”<dependency> <groupId>org.rulii</groupId> <artifactId>rulii-bean-validation</artifactId> <version>1.1.0</version></dependency>It brings rulii core and jakarta.validation:jakarta.validation-api and nothing else. If your messages or @Expr conditions use Jakarta Expression Language, keep an implementation such as org.glassfish.expressly:expressly on the classpath, exactly as before; without one, EL in messages is left as written instead of failing.
Remove Hibernate Validator. The Jakarta bootstrap picks the first provider it finds, so with both on the classpath Validation.buildDefaultValidatorFactory() depends on classpath order. If you cannot remove it, select the provider explicitly:
Validator validator = Validation.byProvider(RuliiValidationProvider.class) .configure() .buildValidatorFactory() .getValidator();Spring Boot. Add this library beside rulii-spring 2.3: adding the dependency is the switch (rulii-spring 2.2 brought the library in itself). Its auto-configuration then pins the application’s Validator bean to this provider, so it is selected even when Hibernate Validator is still on the classpath. Taking Hibernate Validator out is optional: while it is present JPA goes on validating entities with it, and a library that calls Validation.buildDefaultValidatorFactory() itself gets whichever provider comes first. To take it out, keep spring-boot-starter-validation for Boot’s wiring and its EL implementation and exclude hibernate-validator from it. To stay on Hibernate Validator while this library is present, set rulii.validation.enabled=false. See Spring Boot Integration.
The javax.validation namespace is not supported. A project still on it migrates to jakarta.validation first.
2. Bootstrap and Configuration
Section titled “2. Bootstrap and Configuration”Validation.buildDefaultValidatorFactory(), Validation.byProvider, ValidatorFactory, ValidatorContext (usingContext()), unwrap and close work as specified. RuliiConfiguration is the provider-specific configuration, where HibernateValidatorConfiguration was.
| Hibernate Validator | Here |
|---|---|
failFast(true) or property hibernate.validator.fail_fast |
failFast(true); the Hibernate property is honoured, as is rulii.validation.fail_fast |
messageInterpolator, traversableResolver, constraintValidatorFactory, parameterNameProvider, clockProvider, addValueExtractor |
The same calls, consulted as the specification says |
addMapping(InputStream) and META-INF/validation.xml |
Not supported; addMapping throws ValidationException, XML is never read |
Other hibernate.validator.* properties |
Ignored |
allowOverridingMethodAlterParameterConstraint, allowMultipleCascadedValidationOnReturnValues, allowParallelMethodsDefineParameterConstraints |
None; the specification’s rules for method hierarchies are enforced as written |
getterPropertySelectionStrategy, propertyNodeNameProvider |
None; properties are the specification’s getters and fields, nodes carry the property name |
temporalValidationTolerance |
None |
enableExpressionLanguage, constraintExpressionLanguageFeatureLevel, customViolationExpressionLanguageFeatureLevel |
EL is on in constraint messages; in templates built inside a validator it is off until enableExpressionLanguage() on the context. There are no feature levels |
localeResolver, defaultLocale, locales |
None; the locale of a message is the one passed to interpolate, else the locale of the rulii context options the validator was built with |
scriptEvaluatorFactory |
None; scripting is rulii’s (see @Expr below) |
externalClassLoader |
None; bundles are read through the context class loader |
beanMetaDataClassNormalizer, initializeBeanMetaData, predefined-scope factory |
None; metadata is read lazily per class and cached per validator |
constraintMappings, programmatic constraint declaration |
None; declare constraints with annotations, or attach rules with @Validate |
ConstraintValidatorFactory default |
Backed by rulii’s ObjectFactory; with rulii-spring, validators are Spring beans with injection |
Provider-specific options that have no Hibernate counterpart: registry(RuleRegistry) for @Validate, mapper(ConstraintMapper) to change how an annotation becomes rules, and options(RuleContextOptions) for the rulii context validation runs in. See Configuration.
3. Constraints
Section titled “3. Constraints”Standard constraints behave as specified, with the same null semantics and the same applicable types. @Email judges the domain part by shape alone, as Hibernate Validator does, so user@localhost and bob@intranet pass.
Hibernate’s additional constraints exist here under org.rulii.validation.beans.constraints with the same simple names and attributes: @Length, @Range, @URL, @UUID, @CreditCardNumber, @LuhnCheck, @Mod10Check, @Mod11Check, @EAN, @ISBN, @UniqueElements, @Normalized, @CodePointLength, @DurationMin and @DurationMax. A message override written for the Hibernate key (org.hibernate.validator.constraints.Length.message) is honoured for them. Changing the import is the whole migration.
Not provided, and what to use instead:
| Hibernate constraint | Here |
|---|---|
@ScriptAssert |
@Expr at class level: @Expr(value = "#{end.isAfter(start)}", lang = "jakarta-el", errorCode = "trip.end"). lang names any rulii script language (Jakarta EL, GraalJS, Groovy, any JSR-223 engine); alias is not needed, the script sees properties by name and the object as $this; reportOn becomes the placement of the annotation. Jakarta EL can be written as #{...} or ${...}: see Jakarta EL in @Expr and @Bind |
@ParameterScriptAssert |
@Expr on the method or constructor; the script sees the arguments by parameter name and as $parameters |
@ConstraintComposition(OR, ALL_FALSE) |
Compose with a rulii rule attached with @Validate, or a RuleSet |
@Currency |
A custom constraint, or @In from this library over the currency codes you accept |
@BitcoinAddress, country-specific constraints (@CPF, @CNPJ, @TituloEleitoral, @PESEL, @NIP, @REGON, @INN) |
A custom constraint; the Hibernate validator classes can be reused as-is behind your own annotation |
Severities. A constraint may carry one of the payload markers Warning, Info or Fatal from org.rulii.validation.beans.payload to report at that severity instead of ERROR; the violation still appears in the result. Hibernate has no equivalent, so this is additive.
4. Custom Constraint Validators
Section titled “4. Custom Constraint Validators”A ConstraintValidator runs unchanged: one instance per constraint occurrence, initialize once, isValid with the specification’s context. The validator becomes the condition of a rulii rule, and the constraint’s attributes become the rule’s parameters.
| Hibernate Validator | Here |
|---|---|
context.unwrap(HibernateConstraintValidatorContext.class) |
context.unwrap(RuliiConstraintValidatorContext.class); unwrapping a Hibernate type throws a ValidationException whose message names the replacement |
addMessageParameter(name, value), addExpressionVariable(name, value) |
The same two methods on RuliiConstraintValidatorContext; parameters render as {name} in default and custom messages, variables as ${name} in expressions |
withDynamicPayload(Object), getConstraintValidatorPayload |
None |
HibernateConstraintValidator.initialize(descriptor, initializationContext) |
None; the plain initialize(annotation) |
enableExpressionLanguage() on the context |
The same |
buildConstraintViolationWithTemplate, addPropertyNode, addBeanNode, addContainerElementNode, addParameterNode, inIterable, inContainer, getClockProvider, disableDefaultConstraintViolation |
The same |
A validator that needs collaborators is created through the configured ConstraintValidatorFactory, which is backed by rulii’s ObjectFactory; with rulii-spring the Spring object factory makes validators Spring beans. The same constraint can also be mapped to rulii rules directly, without a ConstraintValidator, through a ConstraintMapper.
5. Groups
Section titled “5. Groups”Groups, group inheritance, @GroupSequence on a class and on a sequence interface, @ConvertGroup, and the implicit grouping of constraints declared on an interface all work as specified.
@GroupSequenceProvider has no equivalent. A sequence that depends on the object’s state is a decision, so it belongs in a rule: attach a RuleFlow with @Validate that reads the object and runs what applies, or request the groups per call from the code that knows the state. The flow sees the groups being processed as $groups.
6. Method and Constructor Validation
Section titled “6. Method and Constructor Validation”forExecutables() returns the ExecutableValidator, with all four methods and the specification’s rules on hierarchies. Interception stays with your framework, as it does with Hibernate Validator: Spring’s method validation drives the ExecutableValidator of the configured Validator, so it works with this one; @ValidateOnExecution is read by containers, not by providers.
Parameter names come from the configured ParameterNameProvider; the default tries rulii’s @Param, then reflection, then the compiled bytecode, so real names come back even without -parameters. @Validate and @Expr are accepted on methods and constructors too, validating the arguments or the return value as applyTo says.
7. Messages
Section titled “7. Messages”ValidationMessages.propertiesat the root of the classpath, with locale variants, overrides the defaults, as before.{attribute}references,{key}lookups,${validatedValue},${formatter.format(...)}and the escaping rules work as specified. EL needs an implementation on the classpath.- The default texts are the specification’s Appendix B, with Hibernate’s wording for
@Pattern(must match "{regexp}"). - A configured
MessageInterpolatoris called per violation with the specification’sContext; aMessageInterpolationExceptionsurfaces as itself. - An
@Exprmessage is a rulii template:${validatedValue}and${value}are the validated value, and the error code resolves through the same bundles. A@Validaterule reports whatever message it builds, its error code resolving the same way.
8. Exceptions
Section titled “8. Exceptions”The specification’s API throws the specification’s exceptions. Declaration problems are found when a class is first read for validation, as with Hibernate Validator, and raise ConstraintDeclarationException, ConstraintDefinitionException, UnexpectedTypeException, GroupDefinitionException or ValueExtractorDefinitionException, through subclasses that name the problem. A failure inside validation reaches the caller as a ValidationException. A @Validate name that resolves to nothing raises ValidateRuleNotFoundException; a bad @Expr raises ExprDeclarationException. validateIn, which runs inside a rulii context you own, keeps rulii’s UnrulyException wrapping, as the rest of rulii does.
9. What the Specification Says and This Library Does Not
Section titled “9. What the Specification Says and This Library Does Not”The library is not a certified implementation and does not run the TCK. None of the known deviations changes the outcome for an ordinary bean, and most match Hibernate Validator’s own behaviour. They are listed on the Specification Coverage page, chapter by chapter; the ones a migration is most likely to meet:
- Deliberately excluded:
META-INF/validation.xmland XML constraint mappings;@ValidateOnExecutionand interception; CDI, JSF and JAX-RS integration; JavaFX value extractors;javax.validation. - Supersets, matching Hibernate Validator:
@Min,@Max,@DecimalMinand@DecimalMaxalso acceptdouble,floatandCharSequence;NaNpasses the numeric constraints;-0.0counts as negative; cycle detection is per validation call, so a shared object reached by two paths is reported once; parameter names are recovered from bytecode; a constraint on a field declaredObjectorNumberis accepted and an unsupported runtime value is skipped. - Lenient or different: a missing or mistyped
message,groupsorpayloadattribute raisesIllegalArgumentException; a class-level@GroupSequencemay not list another sequence or a duplicate group; only dotted names in a message are looked up as bundle keys; the one-argumentinterpolateuses the locale captured at build time;validateValuedoes not consult theTraversableResolver;getConstraintDescriptor()andgetMessageTemplate()are null on@Validateand@Exprviolations; aValidatorFactorystays usable afterclose().
10. What You Gain
Section titled “10. What You Gain”The reason to migrate is on the other side of the ledger: constraints that are named, described and tagged rules you can list and trace; cross-field invariants in one @Expr line; business rules that stay out of the bean and are swapped at runtime with @Validate, parameterised per class or method with @Bind; RuleSet and RuleFlow orchestration; scripted conditions in any language; and one engine for validation and the decisions that follow it.