Search code examples
javahibernatehibernate-validator

Use org.hibernate.validator.internal.cfg.context for creating constraint on a method


I am currently working on refactoring a piece of code because it looks like hibernate guys have a bad track record with version compatibilities.

We were using hibernate-validator-5.0.2.Final initially and I have to upgrade it to hibernate-validator-6.0.16.Final. The public classes eg : ConfiguredConstraint.java have been changed to non-public and they don't seem to work anymore now !

I could see a lot of new methods and classes introduced but kind of stuck with the usage.

I need to create constraint on method and there are N number of methods now which I am not able to figure which one to use from this package : org.hibernate.validator.internal.cfg.context

I know this is a very abstract information but if anyone has any idea how to approach this and implement on a high level, would appreciate that !

TIA


Solution

  • You shouldn't use stuff from the internal package directly.

    See the example 12.8 of https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-programmatic-api .

    HibernateValidatorConfiguration configuration = Validation
            .byProvider( HibernateValidator.class )
            .configure();
    
    ConstraintMapping constraintMapping = configuration.createConstraintMapping();
    
    constraintMapping
        .type( Car.class )
            .constructor( String.class )
                .parameter( 0 )
                    .constraint( new SizeDef().min( 3 ).max( 50 ) )
                .returnValue()
                    .valid()
            .method( "drive", int.class )
                .parameter( 0 )
                    .constraint( new MaxDef().value( 75 ) )
            .method( "load", List.class, List.class )
                .crossParameter()
                    .constraint( new GenericConstraintDef<>(
                            LuggageCountMatchesPassengerCount.class ).param(
                                "piecesOfLuggagePerPassenger", 2
                            )
                    )
            .method( "getDriver" )
                .returnValue()
                    .constraint( new NotNullDef() )
                    .valid();
    

    And then you build your ValidatorFactory from this configuration.