Red Hat

In Relation To

The Hibernate team blog on everything data.

Hibernate Validator 6 is going to be the Reference Implementation of Bean Validation 2.0. This Alpha2 release is coordinated with the 2.0.0.Alpha2 release of the Bean Validation specification.

It is also a playground used to validate future enhancements of the Bean Validation specification so feedback on the subjects presented here is very welcome!

Note that Hibernate Validator 6 requires JDK 8 or above.

If you missed the Alpha1 release, consulting its announcement might be beneficial to you before continuing your reading.

What’s new since Alpha1

Improved container element validation support

Container element validation support is the big new feature of Bean Validation 2.0 and it got some more love during this cycle.

Programmatic API and XML support

To obtain the equivalent of:

public class FishTank {

    private Optional<@Valid FishTankModel> model;

    private Map<@Size(min = 3, max = 10) String, @Min(1) Integer> fishCountByType;
}

it is now possible to declare container element type constraints and cascaded validation either via an XML mapping configuration (which is part of the Bean Validation 2.0 specification):

[...]
    <bean class="com.acme.FishTank" ignore-annotations="false">
        <field name="model">
            <containerElementType>
                <valid />
            </containerElementType>
        </field>
        <field name="fishCountByType">
            <containerElementType typeArgumentIndex="0">
                <constraint annotation="javax.validation.constraints.Size">
                    <element name="min">
                        <value>3</value>
                    </element>
                    <element name="max">
                        <value>10</value>
                    </element>
                </constraint>
            </containerElementType>
            <containerElementType typeArgumentIndex="1">
                <constraint annotation="javax.validation.constraints.Min">
                    <element name="value">
                        <value>1</value>
                    </element>
                </constraint>
            </containerElementType>
        </field>
    </bean>
[...]

or via the (implementation specific) programmatic API:

ConstraintMapping newMapping = config.createConstraintMapping();
newMapping
    .type( FishTank.class )
        .property( "model", FIELD )
            .containerElementType()
                .valid()
        .property( "fishCountByType", FIELD )
            .containerElementType( 0 )
                .constraint( new SizeDef().min( 3 ).max( 10 ) )
            .containerElementType( 1 )
                .constraint( new MinDef().value( 1 ) );

Other improvements

We also made a couple of more minor improvements:

  • the TYPE_ARGUMENT node type has been renamed to CONTAINER_ELEMENT (type argument don’t make sense for annotated array elements)

  • we allow per context custom value extractors

  • we allow value extractors to be contributed using the service loader mechanism

  • we allow to specify value extractors using XML configuration

  • we explore the parent classes and interfaces to search the ValueExtractor definition

Support for the new constraints added to Bean Validation 2.0

In the Alpha2 release of Bean Validation 2.0, we introduced the following new constraints:

  • @NotBlank: check that a char sequence is not blank (i.e. not null, and length of trimmed char sequence > 0)

  • @NotEmpty: check that an element (char sequence, collection, array) is not null and not empty

  • @Email: check that a char sequence is a valid email

  • @Positive: check that a number is positive

  • @Negative: check that a number is negative

We added support for these new constraints to Hibernate Validator.

Performance improvements

We started to run a few benchmarks on Hibernate Validator 6 and we fixed a few performance regressions.

6.0.0.Alpha2 is now significantly faster than 5.4, mostly thanks to the new ValueExtractor design.

Getting 6.0.0.Alpha2

To get the release with Maven, Gradle etc. use the GAV coordinates org.hibernate.validator:{hibernate-validator|hibernate-validator-cdi|hibernate-validator-annotation-processor}:6.0.0.Alpha2. Note that the group id has changed from org.hibernate (Hibernate Validator 5 and earlier) to org.hibernate.validator (from Hibernate Validator 6 onwards).

Alternatively, a distribution bundle containing all the bits is provided on SourceForge (TAR.GZ, ZIP).

Feedback, issues, ideas?

To get in touch, use the usual channels:

What’s next?

Bean Validation 2.0 and Hibernate Validator 6 are still under active development. We will release new alphas on a regular basis.

Hibernate Validator 5.4.1.Final

Posted by    |       |    Tagged as Hibernate Validator Releases

A bugfix release

Hibernate Validator 5.4.1.Final is a bugfix release, mostly for corner cases. 5.4.1.Final is a recommended upgrade for everyone.

Here are the most prominent bugfixes of this release:

  • HV-1088 - Fix a concurrency issue in validator initialization that you probably wouldn’t encounter in a normal usage - you’re supposed to use a shared ConstraintValidatorFactory which mitigates the issue

  • HV-1280 - Fix a class loading conflict with Xerces in modular environements (e.g. WildFly)

  • HV-1252 - Fix an issue with the annotation processor and JavaMoney support. Thanks go to Guillaume Husta for this one.

  • HV-1253 - A few TYPE_USE mentions had been mistakenly introduced in 5.4 when backporting from 6 (5.4 still supports Java 6)

We also integrated a new translation, Persian, thanks to Shahram Goodarzi.

And finally, we upgraded our build instructions for the latest JDK 9 early access build.

As usual, you can find the complete list of all addressed issues in the change log.

Getting 5.4.1.Final

To get the release with Maven, Gradle etc. use the GAV coordinates org.hibernate:{hibernate-validator|hibernate-validator-cdi|hibernate-validator-annotation-processor}:5.4.1.Final.

Alternatively, a distribution bundle containing all the bits is provided on SourceForge (TAR.GZ, ZIP).

Feedback, issues, ideas?

To get in touch, use the usual channels:

What’s next?

Bean Validation 2.0 and Hibernate Validator 6 are under active development. We will release a new alpha in the next few days.

As far as Bean Validation 2.0 is concerned, there are very interesting discussions going on about value extraction which is THE big BV 2.0 feature. Come and join us on Bean Validation website to define the future of Bean Validation.

Hibernate Community Newsletter 6/2017

Posted by    |       |    Tagged as Discussions Hibernate ORM

Welcome to the Hibernate community newsletter in which we share blog posts, forum, and StackOverflow questions that are especially relevant to our users.

Articles

Implementing the soft delete pattern with Hibernate is trivial. Check out this article for more details.

Sri Vikram Sundar wrote a very detailed tutorial about integrating Spring MVC, MySQL, and Hibernate.

Stefan Pröll wrote two articles about using Hibernate Search and Spring Boot:

Baeldung features an article about using the Hibernate-specific @Immutable annotation to mark entities that should never be modified, which allow Hibernate to enable some flush-time performance optimizations.

For our Portuguese readers, Rafael Ponte wrote a guide to controlling transactions programmatically in Legacy Systems using Java 8 Lambdas and the Template Pattern. For non-Portuguese readers, you can use Google Translate since most Romance languages are easily translated into English.

Time to upgrade

Hibernate ORM 5.1.5 and 5.2.9 have been released.

Ninth bug-fix release for ORM 5.2

Posted by    |       |    Tagged as Hibernate ORM Releases

The Ninth bug-fix release for Hibernate ORM 5.2 has just been published. It is tagged at https://github.com/hibernate/hibernate-orm/releases/tag/5.2.9

The complete list of changes can be found here (or here for people without a Hibernate Jira account).

For information on consuming the release via your favorite dependency-management-capable build tool, see http://hibernate.org/orm/downloads/

The release bundles can be obtained from SourceForge or BinTray.

Hibernate ORM 5.1.5.Final released

Posted by    |       |    Tagged as Hibernate ORM Releases

We decided to do another release of the 5.1 series to fix critical bugs to be included in an upcoming version of WildFly. This may be the last release of the 5.1 series, so we recommend that you migrate to 5.2 for future bugfixes.

Hibernate ORM 5.1.5.Final:

For information on consuming the release via your favorite dependency-management-capable build tool, see http://hibernate.org/orm/downloads/

Hibernate Community Newsletter 5/2017

Posted by    |       |    Tagged as Discussions Hibernate ORM

Welcome to the Hibernate community newsletter in which we share blog posts, forum, and StackOverflow questions that are especially relevant to our users.

Interviews

Don’t miss our Hibernate developer interviews with Marco Pivetta and Kevin Peters.

If you want to share your story about Hibernate, let us know, and we can share it with our huge community of passionate developers.

Books

Javin Paul, a long-time Java blogger, gives a review of the two best Hibernate books for Java developers.

Thorben Janssen is now writing a Hibernate Tips book, and you can get a free copy if you want to review it.

Articles

Nowadays, many RDBMS support JSON column types and Hibernate makes it very easy to use JSON object as entity attributes as this article demonstrates it.

Encrypting and decrypting column values is easy-peasy when using Hibernate. Check out this article for a detailed tutorial on this topic.

Arnold Gálovics wrote a very good article how the LazyInitializationException works in Hibernate.

Craig Andrews is building a Hibernate SpringCache prototype which acts like a Hibernate second-level cache implementation on top of Spring Cache. The idea is very interesting, and we are looking for your feedback on this topic.

Our colleague, Chris Cranford have a talk about Hibernate Performance at DevNexus, and here are the slides.

If you’re using MySQL, then you should know that we refactored the MySQL Dialects so that it’s much easier for you to match a Hibernate Dialect with a given MySQL server version.

Concurrency Control is a very interesting topic, and if you every wondered how MVCC (Multi-Version Concurrency Control) works, then this article is going to unravel how INERT, UPDATE, and DELETE statements work in MVCC-based database engines.

Thorben Janssen wrote two articles about Hibernate Search, one about custom Analyzers and another one about Facets.

Time to upgrade

Microservices, data and patterns

Posted by    |       |    Tagged as Discussions

One thing you don’t hear enough about in the microservices world is data. There is plenty of info on how your application should be stateless, cloud native, yadayadayada. But at the end of the day, you need to deal with state and store it somewhere.

I can’t blame this blind spot. Data is hard. Data is even harder in a unstable universe where your containers will be killed randomly and eventually. These problems are being tacked though in many fronts and we do our share.

But once you have dealt with the elasticity problem, you need to address a second problem: data evolution. This is even more pernicious in a microservices universe where:

  • The data structure can and will evolve faster per microservice. Remember this individual puppy is supposed to be small, manageable and as agile as a ballet dancer.

  • For your services to be useful, data must flow from one microservice to another without interlock. So they share data structure directly or via copy, implicitly or via an explicit schema, etc. Requiring to release microservices A, B and C together because they share a common data structure is a big no no.

My colleague Edson Yanaga has written a short but insightful book on exactly those problems. How to deal with data in a zero downtime microservice universe. How to evolve your data structure in a safe and incremental way. How do do that with your good old legacy RDBMS. And a few more subjects.

If you are interested in, or embarking in a microservices journey, I recommend you read this focused book. This will make you progress in your thinking.

The cool thing is that this book is free (or rather Red Hat paid the bill). Go grab a copy of Migrating to microservice databases - O’Reilly (you’ll need to register).

Eclipse tools for Hibernate Search

Posted by    |       |    Tagged as Hibernate Search JBoss Tools

I’m glad to announce the second release of the Eclipse plugin for Hibernate Search. In this post I’m describing the changes and new features of the release. Here you can find the first release blog post.

Index Toolkit

The major change of the release is that all functionality, except "Index Rebuild", are now grouped in the Index Toolkit view. To open it, right-click on a configuration in the Hibernate Configurations view and choose "Open Index Toolkit".

Configuration menu items

Here you can find three tabs: Analyzers, Explore Documents, Search. The first two tabs repeat functionality from the first release of the plugin.

Analyzers Toolkit tab
Explore Documents tab

Searching

The new feature of the release is the capability to easily execute the search.

Search tab

The plugin passes the input string from the search text box to the QueryParser which parses it using the specified analyzer and creates a set of search terms, one term per token, over the specified default field. The result of the search pulls back all documents which contain the terms and lists them in a table below.

Demo

What’s next

The next step is to merge this plugin with the JBoss Tools Hibernate plugin. Currently, the Hibernate Search plugin is based on the Hibernate plugin which must be installed beforehand to prevent a "missing required feature" error.

Today we’ll be talking about Hibernate Validator and how you can provide your own constraints and/or validators in a fully self-contained manner. Meaning packaging it all into its own JAR file, in a way that others can use your library by simply adding it to the classpath.

This functionality is based on Hibernate Validator usage of Java’s ServiceLoader mechanism that allows to register additional constraint definitions. But more on the details later.

What can be a real life scenario for building your own library with constraints and sharing it? Well, let’s say that you are building some library with data classes that user might want to validate. As it may be tough to keep track of all such libraries and write/maintain all those constraints for them - Hibernate Validator provides authors of such libraries a possibility to write and share their own validation extensions. Which can be picked up by Hibernate Validator and used to validate your data classes.

Also this ServiceLoader mechanism allows to solve another problem. As you are trying to be a good developer and provide end users of your library only with the relevant classes and hide implementation details from them, you may not want to expose your validator implementation by mentioning it in the validatedBy() parameter of the @Constraint annotation. By using the approach described in this post you can achieve all these thing.

For our examples we will be creating Maven projects with two modules - one will contain validators and represent a "library" that can be shared, another module will be a consumer of this library and will contain some tests.

Enough of the talking, let’s validate some beans! That’s why we all gathered here, right? :)

Using custom annotations and validators

First let’s consider a case of adding your own constraint annotation and a corresponding validator.

Time, it needs time …​

While Hibernate Validator 5.4 supports a wide range of the Java 8 date/time API (and Bean Validation 2.0 will move this support to the specification level), there are some types not supported, one of them being Duration. This type is not describing a point in time so the regular date/time constraints (@Future / @Past) do not make sense for it. So if for instance we wanted to validate that a given duration has a specified minimum length, a new constraint is needed. Let’s call it @DurationMin.

Our new constraint annotation might look like this:

DurationMin.java
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
@ReportAsSingleViolation
public @interface DurationMin {

    String message() default "{com.acme.validation.constraints.DurationMin.message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

    long value() default 0;
    ChronoUnit units() default ChronoUnit.NANOS;

    /**
     * Defines several {@code @DurationMin} annotations on the same element.
     */
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        DurationMin[] value();
    }
}

Now that we have an annotation, we need to create a corresponding constraint validator. To do that you need to implement the ConstraintValidator<DurationMin, Duration> interface, which contains two methods:

  • initialize() - initializes the validator based on annotation parameters

  • isValid() - performs actual validation

An implementation might look like this:

DurationMinValidator.java
public class DurationMinValidator implements ConstraintValidator<DurationMin, Duration> {

    private Duration duration;

    @Override
    public void initialize(DurationMin constraintAnnotation) {
        this.duration = Duration.of( constraintAnnotation.value(), constraintAnnotation.units() );
    }

    @Override
    public boolean isValid(Duration value, ConstraintValidatorContext context) {
        // null values are valid
        if ( value == null ) {
            return true;
        }
        return duration.compareTo( value ) < 1;
    }
}

As we are creating a new constraint annotation, we should also provide a default message for it. This can be done by placing a ContributorValidationMessages.properties property file in the classpath. This property file should contain a key/message pair, where key is the one used in annotation declaration (in our case it’s com.acme.validation.constraints.DurationMin.message) and message is the one you would like to show when validation fails. Our property file looks like so:

ContributorValidationMessages.properties
com.acme.validation.constraints.DurationMin.message = must be greater than or equal to {value} {units}

The bundle ContributorValidationMessages is queried by Hibernate Validator if the standard ValidationMessages bundle doesn’t contain a given message key, allowing library authors to provide default messages for their constraints as part of their JAR.

If you leave everything else as is, your constraint annotation will live its own life without knowing about the presence of validator. Hibernate Validator will not know of the validator as well. So to make sure that Hibernate Validator discovers your DurationMinValidator, you need to create the file META-INF/services/javax.validation.ConstraintValidator and put the fully qualified name of the validator implementation in it:

META-INF/services/javax.validation.ConstraintValidator
com.acme.validation.validators.DurationMinValidator

After all of this, your new constraint annotation on Duration elements can be used like this:

Task.java
public class Task {

    private String taskName;
    @DurationMin(value = 2, units = ChronoUnit.HOURS)
    private Duration timeSpent;

    public Task(String taskName, Duration timeSpent) {
        this.taskName = taskName;
        this.timeSpent = timeSpent;
    }
}

The project structure should look similar to next one:

project structure, align=

The whole source code presented here can be found in the hibernate-demos repository on GitHub.

Use standard constraints for non standard classes

Now let’s consider the case where you would want a standard Bean Validation constraint to support some other type, besides the ones that are already supported.

ThreeTen Extra types validation

As we were talking about date/time related validation, let’s stay on the same topic for this example as well. In this section we will look at ThreeTen Extra types - a great library that provides additional date and time classes to complement those already present in Java.

Bean Validation provides support for validating temporal types via the @Past/@Future annotations. So we would want to use these annotations on ThreeTen Extra types as well. To keep this example simple we will provide validators only for YearWeek and YearQuarter.

Let’s start with implementing ConstraintValidator<Future, YearWeek> interface:

FutureYearWeekValidator.java
public class FutureYearWeekValidator implements ConstraintValidator<Future, YearWeek> {

    @Override
    public void initialize(Future constraintAnnotation) {
    }

    public boolean isValid(YearWeek value, ConstraintValidatorContext context) {
        if ( value == null ) {
            return true;
        }
        return YearWeek.now().isBefore( value );
    }
}

The next step is to provide a list of implemented validators in META-INF/services/javax.validation.ConstraintValidator file:

META-INF/services/javax.validation.ConstraintValidator
com.acme.validation.validators.FutureYearQuarterValidator
com.acme.validation.validators.FutureYearWeekValidator
com.acme.validation.validators.PastYearQuarterValidator
com.acme.validation.validators.PastYearWeekValidator

After this we can package it all in a JAR file and we are ready to use our validators and share them with the world!

In the end our project structure should look similar to this:

project structure, align=

Now you can place @Past/@Future annotations on YearQuarter and YearWeek types like this:

PastEvent.java
public static class PastEvent {

    @Past
    private YearWeek yearWeek;
    @Past
    private YearQuarter yearQuarter;

    public PastEvent(YearWeek yearWeek, YearQuarter yearQuarter) {
        this.yearWeek = yearWeek;
        this.yearQuarter = yearQuarter
    }
}
FutureEvent.java
public static class FutureEvent {

    @Future
    private YearWeek yearWeek;
    @Future
    private YearQuarter yearQuarter;

    public FutureEvent(YearWeek yearWeek, YearQuarter yearQuarter) {
        this.yearWeek = yearWeek;
        this.yearQuarter = yearQuarter
    }
}

You also can find this example at GitHub.

Conclusion

So, as you can see, custom constraint validators can be built and shared in a fully self-contained way. And it can be done in a few simple steps:

  • create a validator implementing the ConstraintValidator interface

  • reference this validator’s fully qualified name in a META-INF/services/javax.validation.ConstraintValidator file

  • (optional) define custom/default messages by adding a ContributorValidationMessages.properties file

  • package it all as a JAR

  • you are ready to share your constraints, people can add them by simply ading your JAR to the classpath

Hibernate OGM 5.1 Final is out

Posted by    |       |    Tagged as Hibernate OGM Releases

I’m happy to announce the latest stable release of Hibernate OGM: Hibernate OGM 5.1 Final

Compared to the latest candidate release, there are not many changes. You can have a look at the 5.1.0.Final changelog to get all the details.

What’s new compared to 5.0 Final?

I’m glad you asked, this version:

If you need to upgrade from a version before 5.1, you can find help on the migration notes.

Does it work with WildFly 10?

Yes, it does.

However, WildFly 10 ships with Hibernate ORM 5.0 and there are a couple of configuration steps to make it work. The easiest way is to download the WildFly modules for Hibernate ORM and Hibernate OGM ; unpack them in the modules folder of your WildFly base directory and set the following property in your persistence.xml:

<property name="jboss.as.jpa.providerModule" value="org.hibernate:5.1"/>

If you are still confused about the process, we explain it with more details in the paragraph 4.5.1. Packaging Hibernate OGM applications for WildFly 10 of the documentation.

Where can I get it?

You can get the required core library using the following Maven coordinates:

  • org.hibernate.ogm:hibernate-ogm-core:5.1.0.Final

and these are the backends currently available for 5.1.0.Final:

  • Cassandra: org.hibernate.ogm:hibernate-ogm-cassandra:5.1.0.Final

  • CouchDB: org.hibernate.ogm:hibernate-ogm-couchdb:5.1.0.Final

  • Infinispan

    • Embedded: org.hibernate.ogm:hibernate-ogm-infinispan:5.1.0.Final

    • Remote: org.hibernate.ogm:hibernate-ogm-infinispan-remote:5.1.0.Final

  • Ehcache: org.hibernate.ogm:hibernate-ogm-ehcache:5.1.0.Final

  • MongoDB: org.hibernate.ogm:hibernate-ogm-mongodb:5.1.0.Final

  • Neo4j: org.hibernate.ogm:hibernate-ogm-neo4j:5.1.0.Final

  • Redis: org.hibernate.ogm:hibernate-ogm-redis:5.1.0.Final

Alternatively, you can download archives containing all the binaries, source code and documentation from Sourceforge.

What’s next?

One of the focus of the next release will be to improve the features supported by the Hot Rod dialect.

How can I get in touch?

You can find us through the following channels:

We are looking forward to hearing your feedback!

back to top