Red Hat

In Relation To Hibernate Validator

In Relation To Hibernate Validator

Hibernate Validator 5.0.0.Alpha2 and 4.3.1.Final

Posted by    |       |    Tagged as Hibernate Validator

Today it's my pleasure to announce the simultaneous release of Hibernate Validator 5.0.0.Alpha2 and 4.3.1.Final.

Hibernate Validator 5

The 5.0.0.Alpha2 release catches up with the public review draft of Bean Validation 1.1 (1.1.0.Beta2). Let's have a closer look at some of the changes in the following.

Method validation

The methods for validating method arguments and return values have been moved from javax.validation.Validator to a new dedicated interface MethodValidator. It is obtained and used like this:

MethodValidator methodValidator = Validation
    .buildDefaultValidatorFactory()
    .getValidator()
    .forMethods();

OrderService myOrderService = ...;
Method placeOrderMethod = ...;
Object[] arguments = ...;

Set<ConstraintViolation<OrderService>> = methodValidator
    .validateParameters(myOrderService, placeOrderMethod, arguments);

Also related to method validation, there is now support for cross-parameter constraints. These come in handy when several parameters of a method or constructor need to be validated together, similar to traditional class-level constraints. The following shows an example:

@ConsistentDateParameters
public void createCalendarEvent(Date start, Date end) {
    //...
}

Opposed to constraints on individual parameters, cross-parameter constraints are specified on the method itself. To make it easy for readers of your code to differentiate cross-parameter constraints from return value constraints, it's recommended to choose a name which clearly expresses the constraint's purpose.

A cross-parameter constraint is defined like this:

@Target({ METHOD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@CrossParameterConstraint(validatedBy = ConsistentDateParametersValidator.class)
@Documented
public @interface ConsistentDateParameters {
    String message() default "{ConsistentDateParameters.message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
}

As you can see, this looks very similar to a normal Bean Validation constraint annotation. The only difference is that the @CrossParameterConstraint meta-annotation is used to specify the constraint's validator. The validator must support Object[] as validated type:

public class ConsistentDateParametersValidator implements ConstraintValidator<ConsistentDateParameters, Object[]> {

    @Override
    public void initialize(ConsistentDateParameters constraintAnnotation) {
        //nothing to do
    }

    @Override
    public boolean isValid(Object[] value, ConstraintValidatorContext context) {
        if ( value.length != 2 ) {
            throw new IllegalArgumentException( "Unexpected method signature" );
        }

        if ( value[0] == null || value[1] == null ) {
            return true;
        }

        if ( !( value[0] instanceof Date ) || !( value[1] instanceof Date ) ) {
            throw new IllegalArgumentException( "Unexpected method signature" );
        }

        return ( ( Date ) value[0] ).before( ( Date ) value[1] );
    }
}

As this validator operates on an array of objects representing the method arguments to be validated, it is required to check the number and types of arguments first. The advantage of this approach is that it allows to implement generic cross-parameter constraints which are not specific to one method:

@AreEqual(indexes={0,1}, message="Passwords must be identical")
public void resetPassword(String password, String confirmedPassword) {
    //...
}

The Bean Validation EG also considers a more type-safe approach, which has its own quirks, though. Let us know what would work best for you.

Integration with CDI

One of the big themes in Bean Validation 1.1 is the integration with CDI. The 5.0.0.Alpha2 release brings initial support for this. So it's possible now to have dependencies injected into constraint validator implementations via CDI:

public class OrderNumberValidator implements ConstraintValidator<ValidOrderNumber, String> {

    @Inject
    private OrderValidationService orderValidationService;

    @Override
    public void initialize(ValidOrderNumber constraintAnnotation) {
        //nothing to do
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return orderValidationService.isValid(value);
    }
}

But that's not all. When invoking a method on a CDI managed bean which has parameter or return value constraints, automatically an interceptor kicks in, which validates the arguments and return value. If either is invalid, a ConstraintViolationException will be thrown. This protects the method implementation from illegal argument values and the caller from illegal return values. So you'll never have to write code like this again:

public void placeOrder(Item item, int quantity) {
    if(item == null) {
        throw new IllegalArgumentException("Item must not be null");
    }
    if(quantity < 1) {
        throw new IllegalArgumentException("Quantity must be at least 1");
    }
    
    //actual implementation
}

Instead this is sufficient:

public void placeOrder(@NotNull Item item, @Min(1) int quantity) {    
    //actual implementation
}

This does not only simplify the implementation, it also makes sure that the caller knows about the constraints, because they are part of the method's public API.

Group conversion

Finally, there is support for the conversion of the validated groups during cascaded validation, a long standing feature request with the Bean Validation spec. Remember, when annotating an element (e.g. a property or method parameter) with @Valid, validation will be propagated to the referenced object(s).

With help of the new ConvertGroup annotation it is now possible to define which group or sequence on the cascaded element shall be validated when a given group is validated on the parent. Let's look at an example:

//validation groups
public interface Complete extends Default {}
public interface BasicPostal {}
public interface FullPostal extends BasicPostal {}

public class Address {
    
    @NotNull(groups = BasicPostal.class)
    String street1;

    @NotNull
    String street2;

    @Size(groups = BasicPostal.class, min = 3)
    String zipCode = "12";

    @Size(groups = FullPostal.class, max = 2)
    String doorCode = "ABC";
}
    
public class User {

    @Valid
    @ConvertGroup.List({
        @ConvertGroup(from = Default.class, to = BasicPostal.class),
        @ConvertGroup(from = Complete.class, to = FullPostal.class)
    })
    Set<Address> addresses = new HashSet<>();
}

When validating a User object with the default group, for the associated addresses the constraints in the BasicPostal group will be validated. When validating a User object with the Complete group, this will lead to a validation of the constraints in the FullPostal group on the user's addresses.

This feature should help with cascaded validations throughout different layers of an application which all define different validation groups.

While these are the major changes of the release, there are some more notable ones, e.g. minor modifications to the metadata API, some changes around ConfigurationSource as well as several bugfixes. Not related to Bean Validation 1.1, we finished the works to clearly separate API, SPI and internal parts of the code base. The changelog has all the details for you.

Hibernate Validator 4.3

While we're heavily working on Hibernate Validator 5 in order to implement revision 1.1 of the Bean Validation spec, we decided to do a maintenance release of Hibernate Validator 4.3, the reference implementation of Bean Validation 1.0.

We fixed a couple of bugs, most notably HV-591. This caused an error when applying the @Email constraint to long strings. Interestingly, this is by far the most reported bug we've had so far in Hibernate Validator with altogether four duplicates. I'm wondering who choses an email address with over 60 characters, but we can validate it now :) Check out the change log for a complete overview of all issues fixed in 4.3.1.

Summing it up

This concludes our tour through the new Hibernate Validator releases.

As usual, both releases can be retrieved from SourceForge (4.3.1.Final, 5.0.0.Alpha2). The Maven coordinates are org.hibernate:hibernate-validator:4.3.1.Final respectively org.hibernate:hibernate-validator:5.0.0.Alpha2. Your feedback is welcome in the forum, the issue tracker and our mailing list. The new features are not described in the Hibernate Validator reference guide yet, so you might be interested in the latest specification draft.

If you have any ideas or proposals around the Bean Validation 1.1 spec, don't hesitate to engage directly with the expert group.

First Alpha release of Hibernate Validator 5

Posted by    |       |    Tagged as Hibernate Validator

Good news for all of you waiting for an early version of Hibernate Validator 5 in order to experiment with the new Bean Validation 1.1 (JSR 349) features. Hibernate Validator 5.0.0.Alpha1 is now available for download in the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:5.0.0.Alpha1 or via SourceForge.

The focus of the release was the alignment of Hibernate Validator with the first early draft of Bean Validation 1.1 (1.1.0.Alpha1). The Hibernate Validator changelog circles for this reason around HV-571 which served as placeholder for those specification changes. Of course the biggest change was the formalization of method validation, but there are other interesting new features as well. For example:

  • In conjunction with method validation it is worth having a look at the ParameterNameProvider interface which helps to identify the parameter of a failing parameter constraint in the resulting ConstraintViolation. The Path API was also extended to provide additional meta information about a failing constraint. You can get the element descriptor via Path.Node#getElementDescriptor (of course you need to iterate to the leaf node of first). The element discriptors themselves got extended by ConstructorDescriptor, MethodDescriptor, ParameterDescriptor and ReturnValueDescriptor.
  • Support for container injection in ConstraintValidator. Check out the new life cycle methods ValidatorFactory#close and ConstraintValidatorFactory#releaseInstance in this context.
  • Expose settings defined in XML in the Configuration API. Refer to the new interface javax.validation.ConfigurationSource, but be aware that there is a follow up issue (BVAL-292) as well.

The easiest way to find out more about these new interfaces and classes is to have a look at the Hibernate Validator test suite where you will find tests for all the mentioned new features.

There are more proposals which are still under active discussion. Feel free to contribute :-)

Given that this is an early draft there will be further changes to the API. For this reason Hibernate Validator 5.0.0.Alpha1 is not a production release. On the other hand, for integrators and tool developers it makes a lot of sense to have an early evaluation to see whether we are on the right track.

Enjoy!

Without further ado, Hibernate Validator 4.3.0.Final is available for download in the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:4.3.0.Final or via SourceForge.

The changelog for this version does not contain much, so let me summarize the most important changes of Hibernate Validator 4.3

  • The package structure got refactored to separate clearly between API, SPI and internal classes. Doing though we deprecated some classes. Make sure to migrate to the new types when upgrading to 4.3 read more
  • slf4j got replaced by JBoss Logging as the main logging framework read more
  • A bunch of new and improved constraints, e.g. MOD11, CNPJ, CPF and TituloEleitoral read more
  • A bunch of performance and quality improvements, in particular we addressed issues around metadata caching read more
  • The Hibernate Validator Annotation Processor can now be used without any additional dependencies which makes it setup easier read more
  • Hibernate Validator 4.3 requires now a Java 6 or 7 runtime

Please check also the Hibernate Validator Migration Guide.

Last but not least, thanks to everyone who was lending a helping hand during the development of Hibernate Validator 4.3 (in case you wanted to help, but missed out - why not helping by translating the documentation? Join the Hibernate Validator project on Zanata and get started...).

Enjoy!

P.S. In case you are waiting for a Validator release which aligns with the first draft of Bean Validation 1.1, have an eye on the JBoss snapshot repository. An initial hibernate-validator-5.0.0-SNAPSHOT won't be far off.

Hibernate Validator 4.3.0.Beta1

Posted by    |       |    Tagged as Hibernate Validator

Moving along the road to a Hibernate Validator 4.3 release I am happy to announce the release of Hibernate Validator 4.3.0.Beta1.

One of our foci this time around was to address existing caching issues. HV-479 addresses the problem that the constraint metadata for a given class would be cached in the so called BeanMetaDataManager without an appropriate eviction policy. In most cases this should not be a problem, but for long running applications with for example hot redeploys it could be. We resolved this issue by introducing SoftLimitMRUCache which has an upper bound for the cached metadata.

HV-564 is another caching related issue. Initially ConstraintValidator instances were only cached if they where created by the Hibernate Validator specific ConstraintValidatorFactoryImpl. Now caching occurs also for custom ConstraintValidatorFactorys.

Two other interesting issues are HV-563 and HV-517. The former allows you to reuse your Configuration instance and call Configuration#buildValidatorFactory() multiple times. The latter introduces the concept of ignoring annotations to the programmatic API. In the XML configuration it has always been possible to do something like this:

    <constraint-mappings
        xmlns="http://jboss.org/xml/ns/javax/validation/mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd">

        <bean class="my.package.MyClass" ignore-annotations="true">
        </bean>
    </constraint-mappings>
Via the programmatic API this is now possible via:
    // ...
    HibernateValidatorConfiguration configuration = ...
    ConstraintMapping mapping = configuration.createConstraintMapping();
    mapping.type( MyClass.class ).ignoreAllAnnotations();
    // ...
Of course ignoreAllAnnotations() is also available on the property level of the API.

Another important focus was on HV-561. This issue identifies the API methods which will change between Hibernate Validator 4.3 to 5 (as much as we can foresee this at the moment). Causes for these changes are Bean Validation 1.1 and the separation between API/SPI and internal packages. This has already been discussed in the previous release blog. Right now we have two new packages org.hibernate.validator.spi.group and org.hibernate.validator.spi.resourceloading containing DefaultGroupSequenceProvider and ResourceBundleLocator respectively. The old versions of these interfaces have been deprecated and will be removed in HV 5. On a side note, right now we have the following packages:

    org.hibernate.validator.cfg
    org.hibernate.validator.constraints
    org.hibernate.validator.group
    org.hibernate.validator.internal
    org.hibernate.validator.messageinterpolation
    org.hibernate.validator.method
    org.hibernate.validator.resourceloading
    org.hibernate.validator.spi
Would it make sense to have (by pushing cfg, constraints, group, messageinterpolation, method and resourceloading one level down):
    org.hibernate.validator.api
    org.hibernate.validator.internal
    org.hibernate.validator.spi
Obviously such a move would break much more client code than the current structure. Let us know what you think.

Last but not least, there are also some news from the Hibernate Validator Annotation Processor which can now be used without any additional dependencies (HV-457). This will make it easier to configure the processor within your build as well as IDE.

Hibernate Validator 4.3.0.Beta1 is available via the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:4.3.0.Beta1 or via SourceForge. The changelog is available here and make sure to check the Hibernate Validator Migration Guide as well.

Feedback is always welcome via the Validator Forum and the project issue tracker.

Enjoy!

A question which came up recently a lot was the question about the release plan for Hibernate Validator 4.3. It is time for an answer.

I used to say that Validator 4.3 will align with Bean Validation 1.1, incorporating any changes required for this specification update. Work on BV 1.1 is still in full swing and it is still time to raise your voice for your long missed validation feature. Check out beanvalidation.org for more information.

Back to Hibernate Validator though. Over the last few months we incorporated a bunch of useful changes and bug fixes into the code base. For example all string based ConstraintValidators work now on any subclass of CharSequence (HV-502) and the email validator now supports internationalized domain names (HV-472, Java 6 required). Or check out the new generic MOD11 constraint (HV-491) and its application in the new constraints CNPJ, CPF and TituloEleitoral (used for Brazilian individual taxpayer and voting registration numbers). We also have some performance improvements via HV-550 and HV-515.

As you can see quite a bunch of useful changes which we want to release as soon as possible. We also want to offer these improvements for users who don't want to upgrade to Bean Validation 1.1 right away (some of the expected changes will break backwards compatibility with Hibernate Validator 4.2). For this reason we just released Hibernate Validator 4.3.0.Alpha1 with the plan to move to a final release as fast as possible. Two more issues are worth mentioning though: HV-481 and HV-484. The former is the switch to JBoss Logging and the latter is the start of a package refactoring which will (once completed) introduce a clear separation between API/SPI and internal parts on a package level. This change is in accordance with the changes already introduced by the other Hibernate projects. Have a look at the Hibernate Validator Migration Guide to see what these changes imply.

Hibernate Validator 4.3.0.Alpha1 is available via the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:4.3.0.Alpha1 or via SourceForge. The changelog is available here. Feedback is welcome via the Validator Forum and the issue tracker.

As a result, Hibernate Validator 5 will become the reference implementation of Bean Validation 1.1.

Thanks to all the people suggesting features and reporting bugs. Special thanks to George Gastaldi, Kevin Pollet and Gunnar Morling for your continuous commitment. You guys rock!

Enjoy!

So it's official Bean Validation 1.1 has started. It has been voted yes by the JCP expert committee yesterday.

I must admit I'm quite furious about Mark Little, the Red Hat representative and my boss, for forgetting to vote on the ballot. But provided he went on vacations last Friday and has a lot on his plate, I forgive him. You owe me though :)

More seriously, Red Hat is committed to make Bean Validation 1.1 a success and I will spend the next couple of days gathering the expert group members to get started as quickly as possible.

In the mean time and to celebrate, have a look at the official beanvalidation.org website. The idea behind the website are simple:

  • execute on the promise to run the spec in an open fashion
  • offer regular updates on the work in progress (see the news section)
  • a one time shop for everything Bean Validation related

There are several ways for you to participate in the process. From joining the development mailing list to joining the expert group full blown. Check out the contribution page.

You might have heard the news: JBoss AS 7 is out :) What does it mean from an Hibernate user perspective?

Before we go that way and if you are in a hurry Pete has written a few getting started guides covering JPA in JBoss AS 7. You might be interested.

Back to the subject: JBoss AS 7 and Hibernate.

Hibernate Core

First of all, JBoss AS 7 comes with Hibernate Core 4. This essentially means that AS 7 will be using the new foundational grounds for Hibernate Core. Hibernate Core 4 comes with many internal changes:

  • A new ServiceRegistry interface: many pieces of Hibernate are now service based and many contracts have been enhanced (like connections and second level caches)
  • A MetadataSources interface: instead of mixing configuration and mapping like the Configuration class was doing, we have now split the concerns and lifecycles
  • A package refactoring splitting classes into api, spi and internals: if your application depends on internals, you know you might get burnt by a minor/micro update
  • A new class loader service (see below)
  • Better logging with consistent error id (our goal is to build an error-id to solution database somewhere over time)
  • A move to Git and GitHub for version control: hopefully this is speeding up community contribution integration

Multi-tenancy

We have also introduced some new features, the most interesting definitely being multi-tenancy (see also here).

New classloader service

Why?

Historically, Hibernate relied on standard class-loading paradigms that targeted JSE and JEE deployment environments. However, with the growth of OSGi and other modular systems like JBoss AS 7, those same approaches no longer always work. So Hibernate needed a new approach that would allow it operate in all possible deployment environments.

How?

In Hibernate 4 we leverage the ServiceRegistry to define a pluggable service for providing interaction with the class-loading of the semantics of the environment in which Hibernate will be run. Specifically, the idea is to allow external entities (the user, the environment developers, etc) to define and plug in a custom scheme for class path interactions. For example, an OSGi container could choose to provide Hibernate (either directly or as its JPA provider) and install a custom service for class loader interactions to override the default one.

Hibernate Core in AS 7

JBoss AS 7 integrates with Hibernate 4.0.0.Beta1, to provide both the EE container managed JPA features and application managed access as well. The AS7 JPA subsystem integrates with Hibernate via the JPA specification SPI interfaces. In earlier releases of JBoss AS, JPA integration code was part of the EJB3 container (reflecting the evolution from EJB entity beans). Moving the JPA integration code into its own subsystem helps simplify the code and makes it easier to make changes.

Quick second-level cache tip

Enabling the (Infinispan) second level cache should be as simple as including the following in your persistence.xml file:

  <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
  <properties>
    <property name="hibernate.cache.infinispan.cachemanager" value="java:jboss/infinispan/hibernate"/>
    <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.infinispan.JndiInfinispanRegionFactory"/>
  </properties>

I (aka Scott Marlow) would like to thank the following people for contributing to the JBoss AS7 JPA subsystem:

  • Stuart Douglas for contributing to the JPA subsystem.
  • Steve Ebersole for contributing to the JPA subsystem (especially Hibernate 4.0 integration).
  • Jaikiran Pai for contributing to the JPA subsystem and answering an amazing number of questions in the forums (JPA + hundreds of other topics).
  • Emmanuel Bernard for answering my never ending JPA 2.0 specification questions.
  • Carlo de Wolf for answering my questions about the EJB3 subsystem (which the new code is based on).

What is next

Improving support for applications that use a different version of Hibernate than is packaged with JBoss AS 7. The plan is to let users deploy the Hibernate jars as well as a hibernate-jbossas7 integration jar. The integration jar will be tailored to the specific couple of Hibernate / JBoss AS version (or families of).

To be clear, Hibernate native applications can already include their own version of Hibernate in JBoss AS 7 simply by including the jar in their deployment. But we want JPA applications to benefit from this enhancement as well. Because it involves specification classes, this requires a bit more work.

We will also include additional tuning options to disable some of the JPA integration (ie prevent the container from starting the persistence unit).

Hibernate Validator and Bean Validation

What's new in AS7 in relation to Bean Validation? The short answer - nothing. It was already awesome ;) The initial version - AS 7.0 - ships with Hibernate Validator 4.1.0.Final. This is the same Validator version as in AS 6 so no change there.

The long answer is that Hibernate Validator 4.2.0.Final merely missed the AS 7.0 release train and an upgrade is planned at the latest in AS 7.1. What will the update mean for AS users? Besides the usual bug fixes and performance improvements, the biggest new feature is the implementation of appendix C of the Bean Validation specification: method level validation.

With this API a design by contract approach is possible which can already be seen in action in the Seam Validation module. Another new feature is the ability to combine the composing constraints with AND and OR operators. There is also a fail fast mode in which validation stops on the first validation error and a new message interpolator which is able to interpolate the validated value.

As you can see AS 7.0 is just the beginning. More is to come in the coming releases...

Hibernate Search

We are working on Hibernate Search 4 which will be compatible with Hibernate Core 4. As a matter of fact, we have already published a compatible version via a Maven SNAPSHOT but expect a first alpha release soon.

Hibernate Search 4 is our chance to fix mistakes from the past. To be honest, the codebase and concepts have aged quite well despite the massive feature shifts we have done in Hibernate Search. Anyways, we are doing some changes including splitting API/SPI/implementations to help people discover when they use a class that is subject to change.

We are also working on a new per index manager to better use some of the new features and design changes of Lucene. This will give you more flexibility on how to index data on a per entity level (sync/async etc).

And remember, go try the blazingly fast, lightweight, modular, hot and incremental deployable, elegantly administrable, domain manageable, first class best of breed JBoss Application Server 7

Happy code/fast deploy/test cycles :)

Steve, Hardy, Scott Marlow and Emmanuel

Hibernate Validator 4.2.0.CR1

Posted by    |       |    Tagged as Bean Validation Hibernate Validator

Hibernate Validator 4.2.0.CR1 is finally ready for download via the JBoss Maven Repository or SourceForge. We promise you won't have to wait so long for 4.2.0.Final. In total we addressed 28 issues. Most of the issues where minor bug fixes, documentation and code refactorings. Thanks you everyone providing bug reports and helping us to make Validator even better :-)

The biggest change is the ability to now also configure method level validation programmatically. To implement this in an unambiguous way we had to make yet some more changes to the programmatic API. Remember how the programmatic API looked like in Beta2? Here is an example:

ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Car.class )
    .property( "manufacturer", FIELD )
        .constraint( NotNullDef.class )
    .property( "licensePlate", FIELD )
        .constraint( NotNullDef.class )
        .constraint( SizeDef.class )
            .min( 2 )
            .max( 14 )
    .property( "seatCount", FIELD )
        .constraint( MinDef.class )
            .value ( 2 )
.type( RentalCar.class )
    .property( "rentalStation", METHOD)
        .constraint( NotNullDef.class ); 

With the CR1 API the same example looks like:

ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Car.class )
    .property( "manufacturer", FIELD )
        .constraint( new NotNullDef() )
    .property( "licensePlate", FIELD )
        .constraint( new NotNullDef() )
        .constraint( new SizeDef()
            .min( 2 )
            .max( 14 ) )
    .property( "seatCount", FIELD )
        .constraint( new MinDef()
            .value ( 2 ) )
.type( RentalCar.class )
    .property( "rentalStation", METHOD )
        .constraint( new NotNullDef() ); 

As you can see the difference is that you now have to instantiate the definition classes. That's all. Not too bad, right? Programmatic method level validation looks like this:

ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Car.class )
    .method( "drive", String.class, Integer.class )
        .parameter( 0 )
            .constraint( new NotNullDef() )
            .constraint( new MinDef().value ( 1 ) )
        .parameter( 1 )
            .constraint( new NotNullDef() )
        .returnValue()
            .constraint( new NotNullDef() )
    .method( "check" )
        .returnValue()
            .constraint( new NotNullDef() );   

You find the full change log for this release here. Please provide feedback via the Validator Forum and the Jira issue tracker.

Thanks to Gunnar and Kevin to once more were driving most of the work.

Enjoy!

P.S. If you have any opinion what should go into Bean Validation 1.1 let us know!

Hibernate Validator 4.2.0.Beta2

Posted by    |       |    Tagged as Bean Validation Hibernate Validator

Hibernate Validator 4.2.0.Beta2 is bottled up and ready for consumption via the JBoss Maven Repository or SourceForge.

Since Beta1 we have been focusing on method level validation details and bug fixes. One important issue in this regard is HV-421 which defines the behavior of parameter constraint validation. Generally a logical AND is used to combine all constraints defined within a class hierarchy on a given field or method. Doing the same for method parameter constraints, however, causes ambiguities with the definition of Programming by contract where subtypes may only weaken preconditions defined by supertypes. In order to support this one would have to combine all parameter constraints within a hierarchy using an OR. A conservative alternative (the one we chose for this release) is to prohibit multiple parameter constraints on the same parameter within a class hierarchy. HV-421 discusses in more detail. We are very interested in feedback on this.

Another method level validation related feature is the extension of the meta data API (HV-440). We introduced three more interfaces TypeDescriptor, MethodDescriptor and ParameterDescriptor which you can all find in the org.hibernate.validator.method.metadata package. Here is an usage example:

 MethodValidator validator = Validation.byProvider( HibernateValidator.class )
    .configure()
    .buildValidatorFactory()
    .getValidator()
    .unwrap( MethodValidator.class );

TypeDescriptor typeDescriptor = validator.getConstraintsForType( clazz );
...
Set<MethodDescriptor> constrainedMethods = descriptor.getConstrainedMethods();
...
List<ParameterDescriptor> parameterConstraints = methodDescriptor.getParameterConstraints();
ParameterDescriptor parameterDescriptor = parameterConstraints.get( 0 );
assertTrue( parameterDescriptor.hasConstraints() );
...
Note: MethodValidator.validateParameters was renamed into MethodValidator.validateAllParameters (HV-415).

To mention at least one method level validation unrelated feature - Hibernate Validator has now a fail fast option. When enabled, validation will terminate on the first validation error. This could be interesting for large object graph validation. You can enable the fail fast flag for example via:

ValidatorFactory factory = Validation.byProvider( HibernateValidator.class )
                             .configure()
                             .failFast( true )
                             .buildValidatorFactory();
You find the full change log for this release here. Please provide feedback via the Validator Forum and the Jira issue tracker.

Enjoy!

P.S. For all the Seam people out there. Gunnar started a new Seam 3 module called SeamValidation which offers amongst other a CDI extension for method level validation. Check it out!

P.P.S. Make sure to also provide feedback on what we should include into Bean Validation 1.1

Vote for Pedro

Posted by    |       |    Tagged as Bean Validation Hibernate Validator

Well not really ;)

We have talked about Gunnar and Kevin that have and are still doing an awesome job on Hibernate Validator, especially for the last release and the current one in development. Please consider voting for them for the JBoss.org recognition awards.

Gunnar Morling is nominated in the:

The new method validation feature is all his for example.

And Kevin Pollet is nominated in the:

He fixed many bugs but also added some nice cool features like Joda-time support.

back to top