Red Hat

In Relation To

The Hibernate team blog on everything data.

Hibernate Community Newsletter 3/2016

Posted by Vlad Mihalcea    |       |    Tagged as Discussions Hibernate ORM

Starting this year, we are hosting a series of articles focused on the Hibernate community. We share blog posts, forum and StackOverflow questions that are especially relevant to our users.

Articles

Eugen Paraschiv wrote a very detailed article about auditing entity changes, comparing JPA callback annotations with Hibernate Envers and Spring Data JPA Auditing.

The guys at Plumbr have raised awareness of how the MySQL JDBC driver handles database-generated warning messages. We created a JIRA issue for this, and we’re discussing various possibilities for handling it without affecting other database drivers which are more efficient in this regard.

I wrote an article about the AUTO flush mode handling strategies employed by the Hibernate implementation of the Java Persistence API and the Hibernate native API.

WildFly 10 has just been released with support for Hibernate 5.

Videos

Thorben Janssen recorded a video explaining the first-level cache.

It’s my pleasure to announce the release of Hibernate Validator 5.2.3.Final!

Wait, didn’t we already do another Hibernate Validator release earlier this month? That’s right, indeed we pushed out the first Alpha of the 5.3 family a couple of days ago. And normally, that’d mean that there would be no further releases of earlier version families.

But in this case we decided to do an exception from the rule as we noticed that Hibernate Validator couldn’t be used with Java 9 (check out issue HV-1048 if you are interested in the details). As we don’t want to keep integrators and users of Hibernate Validator from testing their own software on Java 9, we decided to fix that issue on the current stable release line (in fact we strongly encourage you to test your applications on Java 9 to learn as early as possible about any potential changes you might need to make).

While we were at it, we backported some further bugfixes from 5.3 to 5.2, amongst them one for ensuring compatability with the Google App Engine. As always, you can find the complete list of fixes in the changelog.

Where do I get it?

Use the GAV coordinates org.hibernate:{hibernate-validator|hibernate-validator-cdi|hibernate-validator-annotation-processor}:5.2.3.Final to fetch the release with Maven, Gradle etc. Alternatively, you can find distribution bundles containing all the bits on SourceForge (TAR.GZ, ZIP).

Found a bug? Have a feature request? Then let us know through the following channels:

Eclipse tools for Hibernate Search

Posted by Dmitry Bocharov    |       |    Tagged as Hibernate Search JBoss Tools

I’m glad to announce the first release of the Eclipse plugin for Hibernate Search. In this post I want to describe its features and ask you for any comments, positive or (even more important for me) negative.

Installation

The plugin was made as a feature of jbosstools-hibernate plugin, which can be downloaded and installed on its own or together with the full JBoss Tools distribution. After that you can install the Hibernate Search plugin via the Eclipse Marketplace.

All requirements, such as eclipse version and platform support, are listed in the link.

In order to work with Hibernate Search you have to set the Hibernate configuration properties hibernate.search.default.directory_provider and hibernate.search.default.indexBase.

Functionality

The plugin was thought to be some kind of a Luke tool inside Eclipse. It was thought to be more convenient than launching a separate application, and picks up the configuration directly from your Hibernate configuration.

Three options were added to the console configurations: Index rebuild, Explore documents and Try analysers.

Index Rebuild Action screenshot

Index rebuild

When introducing Hibernate Search in an existing application, you have to create an initial Lucene index for the data already present in your database.

The option "Rebuild index" will do so by re-creating the Lucene index in the directory specified by the hibernate.search.default.indexBase property.

Screenshot of Hibernate Search indexed entities
Screenshot for Hibernate Search configuration properties

Explore Documents

After creating the initial index you can now inspect the Lucene Documents it contains.

All entities annotated as @Indexed are displayed in the Lucene Documents tab. Tick the checkboxes as needed and load the documents. Iterate through the documents using arrows.

Screenshot of Lucene Documents inspection

Try the Analyzers

The "try analyzers" instrument allows you to view the result of work of different Lucene Analyzers. The combo-box contains all classes in the workspace which extend org.apache.lucene.analysis.Analyzer, including custom implementations created by the user. While you type the text you want to analyse, the result immediately appears in the AnalysisResultTab view.

Screenshot of Try Analyzers

Possible issues

One problem which you might have is that "Index rebuild" option seems to do nothing. As a temporary workaround try to set the Hibernate configuration property "hibernate.search.autoregister_listeners" to "true" explicitly.

If you have any other problems, such as unexpected behaviour, strange windows with exceptions or any errors in the Error log view feel free to contact me directly anywhere or just create an issue in the plugin github page.

Plans

  • Make options "Index rebuild" and "Explore documents" available not only for configurations, but also for concrete entities under session factory.

  • Make Lucene Documents view more comfortable to use and add there more features from Luke tool, for example, the ability to search over documents.

  • Increasing stability of the plugin and implementing your suggestions!

Hibernate Validator 5.3.0.Alpha1 is out

Posted by Gunnar Morling    |       |    Tagged as Hibernate Validator Releases

It’s my pleasure to announce the first release of Hibernate Validator 5.3!

The overarching idea for the 5.3 timeline is to prototype several features which may potentially be standardized in the Bean Validation 2.0 specification. For instance we’ll work on a solution for the long-standing request for sorting the constraints on single properties.

If you’d like to see any specific features addressed in that prototyping work (and eventually included in BV 2.0), then please get in touch and let us know which are the most important things you are missing from the spec. We’ve compiled a first list of issues we are considering for inclusion in BV 2.0. For sure we cannot address all of them, so it’ll greatly help if you tell us what would be most helpful to you.

Dynamic payloads for constraints

To get things rolling, the Alpha 1 allows to you to enrich custom constraint violations with additional context data. Code examining constraint violations can access and interpret this data in a safer way than by parsing string-based constraint violation messages. Think of it as a dynamic variant of the existing Bean Validation payload feature.

As an example, let’s assume we have a constraint @Matches for making sure a long property matches a given value with some tolerance:

public static class Package {

    @Matches(value=1000, tolerance=100)
    public long weight;
}

If the annotated value is invalid, the resulting constraint violation should have a specific severity, depending on whether the value lies within the given tolerance or not. That severity value could then for instance be used for formatting the error specifically in a UI.

The definition of the @Matches constraint is nothing new, it’s just a regular custom constraint annotation:

@Retention(RUNTIME)
@Constraint(validatedBy = { MatchesValidator.class })
@Documented
public @interface Matches {

    public enum Severity { WARN, ERROR; }

    String message() default "Must match {value} with a tolerance of {tolerance}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

    long value();
    long tolerance();
}

The constraint validator is where it’s getting interesting:

public class MatchesValidator implements ConstraintValidator<Matches, Long> {

    private long tolerance;
    private long value;

    @Override
    public void initialize(Matches constraintAnnotation) {
        this.value = constraintAnnotation.value();
        this.tolerance = constraintAnnotation.tolerance();
    }

    @Override
    public boolean isValid(Long value, ConstraintValidatorContext context) {
        if ( value == null ) {
            return true;
        }

        if ( this.value == value.longValue() ) {
            return true;
        }

        HibernateConstraintValidatorContext hibernateContext = context.unwrap(
                HibernateConstraintValidatorContext.class
        );
        hibernateContext.withDynamicPayload(
                Math.abs( this.value - value ) < tolerance ? Severity.WARN : Severity.ERROR
        );

        return false;
    }
}

In isValid() the severity object is set via HibernateConstraintValidatorContext#withDynamicPayload(). Note that the payload object must be serializable in case constraint violations are sent to remote clients, e.g. via RMI.

Validation clients may then access the dynamic payload like so:

HibernateConstraintViolation<?> violation = violations.iterator()
    .next()
    .unwrap( HibernateConstraintViolation.class );

if ( violation.getDynamicPayload( Severity.class ) == Severity.ERROR ) {
    // ...
}

What else is there?

Other features of the Alpha 1 releases are improved OSGi support (many thanks to Benson Margulies for this!), optional relaxation of parameter constraints (kudos to Chris Beckey!) and several bug fixes and improvements, amongst them support for cross-parameter constraints in the annotation processor (cheers to Nicola Ferraro!).

You can find the complete list of all addressed issues in the change log. To get the release with Maven, Gradle etc. use the GAV coordinates org.hibernate:{hibernate-validator|hibernate-validator-cdi|hibernate-validator-annotation-processor}:5.3.0.Alpha1. Alternatively, a distribution bundle containing all the bits is provided on on SourceForge (TAR.GZ, ZIP).

To get in touch, use the following channels:

Hibernate Community Newsletter 2/2016

Posted by Vlad Mihalcea    |       |    Tagged as Discussions Hibernate ORM

Starting this year, we are hosting a series of articles focused on the Hibernate community. We share blog posts, forum and StackOverflow questions that are especially relevant to our users.

Articles

A very interesting project is Apache Trafodion, which aims to build a transactional SQL engine on top of Hadoop. We’d like to thanks the Trafodion team for writing a Hibernate Dialect, therefore making it possible to access Hadoop from a Hibernate data access layer. Give it a try and let us know what you think.

Thorben Janssen wrote an article about calling native SQL queries from JPA.

Romain Manni-Bucau demonstrates how you can integrate JPA pagination with Java 8 Streams.

Michael J. Simons, who gave us the idea of writing the JPA test case templates, describes the EuregJUG site architecture which, along other open-source frameworks, makes use of Hibernate for accessing data.

JPA test case templates

Posted by Vlad Mihalcea    |       |    Tagged as Hibernate ORM

In the good spirit of open source, any Hibernate ORM issue should be accompanied by a replicating test case. The test case is a proof that the issue really exists and is reproducible.

To simplify the test case writing procedure, Hibernate provides a series of templates that you can just grab from GitHub. Thanks to these tests, the issue reporter can focus on the actual persistence-related problem since the templates take care of all the bootstrapping logic.

Previously, the test case templates were available only for the Hibernate native API, which was fine as long as you’re familiar with it. Because many projects use Hibernate as a JPA provider, it’s very convenient to offer a JPA bootstrap environment as well. And that’s what we did.

Next, I’m going to provide a step-by-step guide for writing a JPA-based Hibernate test case.

First, you need to either fork or download the hibernate-test-case-templates GitHub repository.

This repository has an orm folder containing two Maven modules:

hibernate-orm-4

To replicate issues for Hibernate 4.x

hibernate-orm-5

To replicate issues for Hibernate 5.x

Each module has three templates:

ORMStandaloneTestCase.java

This one is a Hibernate native test case (you get access to the SessionFactory and you operate with a Session), but it requires you to manually bootstrap the Hibernate environment.

ORMUnitTestCase.java

This is also a Hibernate native test case (you get access to the SessionFactory and you operate with a Session), but the bootstrapping is provided on your behalf.

JPAUnitTestCase.java

This is the new template that needs to be used for replicating an issue using the Java Persistence API (you get access to the EntityManagerFactory and you operate with an EntityManager).

When replicating an issue with the Hibernate native API, the ORMUnitTestCase is usually preferred.

This post focuses on the newly added JPAUnitTestCase which looks like this:

public class JPAUnitTestCase {

    private EntityManagerFactory entityManagerFactory;

    @Before
    public void init() {
        entityManagerFactory = Persistence.createEntityManagerFactory( "templatePU" );
    }

    @After
    public void destroy() {
        entityManagerFactory.close();
    }

    // Entities are auto-discovered, so just add them anywhere on class-path
    // Add your tests, using standard JUnit.
    @Test
    public void hhh123Test() throws Exception {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        // Do stuff...
        entityManager.getTransaction().commit();
        entityManager.close();
    }
}

The EntityManagerFactory is created before every test case and destroyed afterwards. The test case logic goes inside the @Test Junit method.

You should name the test method after the Hibernate JIRA issue you are trying to replicate.

The EntityManagerFactory uses the templatePU Persistence Unit, which is located under src/test/resources/META-INF/persistence.xml. By default, this file looks like this:

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="templatePU" transaction-type="RESOURCE_LOCAL">

        <description>Hibernate test case template Persistence Unit</description>
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <exclude-unlisted-classes>false</exclude-unlisted-classes>

        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>

            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1"/>
            <property name="hibernate.connection.username" value="sa"/>

            <property name="hibernate.connection.pool_size" value="5"/>

            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>

            <property name="hibernate.max_fetch_depth" value="5"/>

            <property name="hibernate.cache.region_prefix" value="hibernate.test"/>
            <property name="hibernate.cache.region.factory_class"
                      value="org.hibernate.testing.cache.CachingRegionFactory"/>

            <!--NOTE: hibernate.jdbc.batch_versioned_data should be set to false when testing with Oracle-->
            <property name="hibernate.jdbc.batch_versioned_data" value="true"/>

            <property name="javax.persistence.validation.mode" value="NONE"/>
            <property name="hibernate.service.allow_crawling" value="false"/>
            <property name="hibernate.session.events.log" value="true"/>
        </properties>

    </persistence-unit>
</persistence>

The persistence.xml configuration file is already set up for bootstrapping Hibernate, offering a reasonable default environment. In case you want to provide a different configuration, like using JTA with a stand-alone Transaction Manager, you’ll have to change the default configuration.

All entities are auto-discovered, so you can place them anywhere on classpath. In this example, we are going to use the following entity:

@Entity
public class Event {

    @Id
    @GeneratedValue
    private Long id;

    @Temporal(TemporalType.TIMESTAMP )
    private Date createdOn;

    public Event() {
    }

    public Event(Date createdOn) {
        this.createdOn = createdOn;
    }

    public Long getId() {
        return id;
    }

    public Date getCreatedOn() {
        return createdOn;
    }
}

Now, the persistence logic can be added to the JUnit test method:

@Test
public void hhh123Test() throws Exception {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();

    Event event = new Event( new Date() );
    entityManager.persist( event );

    Event dbEvent = entityManager.createQuery(
            "select e " +
            "from Event e", Event.class)
        .getSingleResult();
    assertEquals(event.getCreatedOn(), dbEvent.getCreatedOn());

    entityManager.getTransaction().commit();
    entityManager.close();
}

That’s it! You can now provide a Hibernate test case using the standard Java Persistence API.

JBoss Community Asylum - Hibernate Strikes Back Episode V

Posted by Max Andersen    |       |    Tagged as JBoss Asylum

Emmanuel talks with Steve Ebersole about what is new and interesting in Hibernate 5.

Find it all in the Show notes and episode.

Have fun!




7th bug-fix release for ORM 5.0

Posted by Steve Ebersole    |       |    Tagged as Hibernate ORM Releases

The 7th bug-fix release for Hibernate ORM 5.0 has just been tagged and published.

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/

For those of you allergic to dependency-management-capable build tools, the release bundles can be obtained from SourceForge or BinTray.

Hibernate Community Newsletter 1/2016

Posted by Vlad Mihalcea    |       |    Tagged as Discussions Hibernate ORM

Happy New Year, everyone!

Starting this year, we are going to host a series of articles focused on the Hibernate community. We are going to share blog posts, forum and StackOverflow questions, that are especially relevant to our users.

Articles

Thorben Janssen, who regularly writes about JPA and Hibernate topics, has summarized the most typical logging configurations in a Hibernate Logging Guide.

For our Portuguese readers, Rafael Ponte has written a very interesting article about bidirectional relationships and the caveats of not properly synchronizing both ends of a bidirectional association.

One topic, I always wanted to investigate in great details, is about the aggressive connection release behavior employed for JTA transactions. For high-performance data access platforms, it’s worth checking if the Java EE application server can operate successfully even without aggressive connection release.

Version 5.5.2.Final is now available, our latest stable version sporting integration with Hibernate ORM 5 and Apache Lucene 5.3 - the state of the art.

Creating this version to be compatible with these two great OSS projects kept us busy for a good deal of this past year; I remember discussing this option with superstar OSS contributors Uwe Schindler (Apache Lucene developer) and Gustavo Nalle (Infinispan developer) at FOSDEM in January 2015! I am grateful to both for their guidance and suggestions, as driving progress forward is sometimes challenging when we strive to keep backwards compatibility as best as we can.

On top of that, our same small but amazing team as been working hard on Hibernate OGM 5, a bit of Hibernate Validator, incredible performance improvements on Hibernate ORM "classic" and is still tinkering on the internals of Hibernate Search to make an Elasticsearch backend an alternative to plain Lucene.

Feel like helping with the Elasticsearch integration?

Version 5.6 will feature an experimental integration with Elasticsearch. Early feedback would be very welcome! If you feel like helping, quite some code is integrated in the master branch already and there are clear TODO and FIXME comments to be found in the code.

Feel free to join the hacking! But best to let us know which area you feel like working on to avoid duplication of efforts and conflicting patches.

The 5.5.2.Final release and our great community

Technically I pushed the release button the 24th, but I couldn’t publish the blog until now because of travels.

On top of the improvements from previous 5.5.1.Final release which sported significant performance improvements, this version now incorporates several important corrections by Yoann Rodière and Guillaume Smet around metadata which was producing incorrect range queries for embedded numeric types.

Yoann also contributed another great performance improving patch, by limiting the recursion triggered by @ContainedIn more strictly, by considering the indexed paths and not just the recursion depth. You might not notice this if you have very simple flat models, but this can provide a very significant boost for all those of you using Hibernate Search to index rich models with extensive usage of @ContainedIn annotations.

Many thanks to Yoann and Guillaume, they are "power users" who do the right thing: their hands-on regular feedback is invaluable, not to mention they send such great patches for everybody else to benefit from. Not least, this is very encouraging for us: let us know which great things you’re building with these libraries!

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-search-orm</artifactId>
   <version>5.5.2.Final</version>
</dependency>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.0.6.Final</version>
</dependency>
<dependency>
   <groupId>org.apache.lucene</groupId>
   <artifactId>lucene-core</artifactId>
   <version>5.3.1</version>
</dependency>

How to get this release

Everything you need is available on Hibernate Search’s web site. Download the full distribution from here, or get it from Maven Central using the above coordinates, and don’t hesitate to reach us in our forums or mailing lists.

back to top