Red Hat

In Relation To Hibernate ORM

In Relation To Hibernate ORM

Third Candidate Release for ORM 5.0

Posted by Steve Ebersole    |       |    Tagged as Hibernate ORM Releases

Yesterday I released the third candidate release for Hibernate ORM 5.0 (5.0.0.CR3). We felt another CR was warranted because we had some minor integration (SPI) work that we needed to make in to Final, but too much development had happened since the second CR to be considered risk free to just include everything into Final. At any rate CR3 got lots of great TLC :) The complete set of changes can be seen in the Jira changelog. The main changes include:

Minor changes to the caching SPI

Essentially passing Session along to the various region access strategy methods to allow integrating with non-JDBC transactions.

Work on schema tooling

Improved namespace (catalog/schema) support overall in schema tools. Improved handling of views and synonyms for migrating and validating.

Work on bytecode enhancement

Lots of fixes based on feedback.

Consistency in Transaction API

A few changes were made to the JDCB-based TransactionCoordinator to work more like in JTA environments. Specifically:

  • implemented support for marking the Transaction for rollback-only.

  • transaction is now rolled back automatically on a failed commit.

Work on the documentation

Besides updating the content, the content has been split into 3 separate guides:

  • User Guide

  • Domain Model Mapping Guide

  • Integrations Guide

How to get it

Additionally many other improvements and bugfixes are included. See https://hibernate.atlassian.net/projects/HHH/versions/20150 for the complete list of changes.

As always, see http://hibernate.org/orm/downloads/ for information on obtaining the releases.

Map me if you can - Advanced embeddable mappings

Posted by Gunnar Morling    |       |    Tagged as Hibernate ORM

The other day I came across an interesting mapping challenge which I thought may be worth sharing. If you are a seasoned JPA user, it will probably be nothing new to you, but those not as experienced may find it helpful :)

TL;DR - JPA let’s you override database columns for embedded objects but also for collections of embedded objects; @AttributeOverride and @AssocationOverride can be used for that.

Let’s assume the following entity model representing a person and their home and business address:

Entity model

The interesting part is that Person has two associations with Address, one with the "homeAddress" role and another one with the "businessAddress" role. Address in turn has one ore more address lines.

When mapping these types with JPA, Person naturally becomes an entity. As there is a composition relationship between Person and Address, the latter is mapped with @Embeddable. The same goes for AddressLine, which also is an @Embeddable, contained within an element collection owned by Address.

So you’d end up with these classes:

@Entity
public class Person {

    @Id
    private long id;
    private String name;
    private Address homeAddress;
    private Address businessAddress;

    // constructor, getters and setters...
}
@Embeddable
public class Address {

    private boolean active;

    @ElementCollection
    private List<AddressLine> lines = new ArrayList<AddressLine>();

    // constructor, getters and setters...
}
@Embeddable
public class AddressLine {

    private String value;

    // constructor, getters and setters...
}

@AttributeOverride

Let’s fire up a session factory with these types (this uses the brand-new bootstrapping API coming in Hibernate ORM 5) and see how that goes:

StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
    .applySetting( AvailableSettings.SHOW_SQL, true )
    .applySetting( AvailableSettings.FORMAT_SQL, true )
    .applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" )
    .build();

SessionFactory sessionFactory = new MetadataSources( registry )
    .addAnnotatedClass( Person.class )
    .buildMetadata()
    .buildSessionFactory();

Hum, that did not go too well:

org.hibernate.MappingException: Repeated column in mapping for entity:
org.hibernate.bugs.Person column: active (should be mapped with insert="false" update="false")

Of course this makes sense; As Address is embedded twice within Person, its properties must be mapped to unique column names within the Person table. The @AttributeOverride annotation can be used for that:

@Entity
public class Person {

    @Id
    private long id;
    private String name;

    @AttributeOverride(name = "active", column = @Column(name = "home_address_active"))
    private Address homeAddress;

    @AttributeOverride(name = "active", column = @Column(name = "business_address_active"))
    private Address businessAddress;

    // constructor, getters and setters...
}

With that, the session factory boots successfully. But let’s take a look at the tables that get created:

create table Person (
    id bigint not null,
    business_address_active boolean,
    home_address_active boolean,
    name varchar(255),
    primary key (id)
)

create table Person_lines (
    Person_id bigint not null,
    "value" varchar(255)
)

@AssociationOverride

The Person table looks alright, but there is only a single table for the address lines. That’s a problem as it means there is no way to tell apart the lines of the business address from the lines of the home address when reading back a person from the database.

So what to do? @AttributeOverride is of no help this time, as it’s not a single column which needs to be re-defined but an entire table. But luckily, @AttributeOverride has a companion, @AssociationOverride. This annotation can be used to configure the required tables in this case:

@Entity
public class Person {

    @Id
    private long id;
    private String name;

    @AttributeOverride(name = "active", column = @Column(name = "home_address_active"))
    @AssociationOverride(name = "lines", joinTable = @JoinTable(name = "Person_HomeAddress_Line"))
    private Address homeAddress;

    @AttributeOverride(name = "active", column = @Column(name = "business_address_active"))
    @AssociationOverride(name = "lines", joinTable = @JoinTable(name = "Person_BusinessAddress_Line"))
    private Address businessAddress;

    // constructor, getters and setters...
}

Et voilĂ , now you’ll get the DDL for creating the Person table and two different tables for the address lines:

create table Person (
    id bigint not null,
    business_address_active boolean,
    home_address_active boolean,
    name varchar(255),
    primary key (id)
)

create table Person_BusinessAddress_Line (
    Person_id bigint not null,
    "value" varchar(255)
)

create table Person_HomeAddress_Line (
    Person_id bigint not null,
    "value" varchar(255)
)

IntelliJ IDEA, Mac OS X and Hibernate ORM

Posted by Emmanuel Bernard    |       |    Tagged as Hibernate ORM

Hibernate ORM, IntelliJ IDEA and Mac OS X have been a pretty tough combination to work with since our move to Gradle. It’s not exactly anyone’s fault but the combination of

  • gradle / IntelliJ integration

  • JDK 6 running IntelliJ IDEA

  • Hibernate ORM advanced use of Gradle and of custom plugins

made for a long and painful journey.

These days are over. Steve found the last blocking issue and you can now import Hibernate ORM natively in IntelliJ IDEA.

Importing Hibernate ORM in IntelliJ IDEA on Mac OS X

git clone git@github.com:hibernate/hibernate-orm.git
  • Open IntelliJ IDEA

  • File → Open

  • Select hibernate-orm

  • The defaults should be good

    • Make especially sure that you select Use default gradle wrapper

    • I use Gradle JVM to 1.8

  • Click OK and let it work and download the internet

You now have a properly imported Hibernate ORM project :)

This worked on Mac OS X 10.10.4 and IntelliJ IDEA CE 14.1.4.

Importing Hibernate ORM in NetBeans on Mac OS X

And this incidentally fixed an import bug for NetBeans.

  • Open NetBeans

  • Install the Gradle plugin

  • Open project

  • Select hibernate-orm

This worked on Mac OS X 10.10.4 and NetBeans 8.0.2.

Second Candidate Release for 5.0

Posted by Steve Ebersole    |       |    Tagged as Hibernate ORM Releases

The second candidate release for Hibernate ORM 5.0. CR2 was required because of a bug in how class-loading worked in certain managed JPA environments. The details can be found in HHH-9887. The main changes since CR1 include:

Corrected ClassLoader usage

This is the blocking issue mentioned above. The problem would occur in environments passing a "temp ClassLoader" into Hibernate via the JPA integration SPI (javax.persistence.spi.PersistenceUnitInfo#getNewTempClassLoader) and manifest itself as ClassCastExceptions.

Second-level caching SPI improvement

The second-level caching SPI was improved, allowing the caching providers to generate cache keys. This includes the addition of the following methods:

  • org.hibernate.cache.spi.access.EntityRegionAccessStrategy#generateCacheKey

  • org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#generateCacheKey

  • org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy#generateCacheKey

Improved cache-by-reference support

For those making use of caching immutable entities by reference (rather than by "disassembled" state), an additional performance improvement is included in CR2.

Ability to disable auto-quoting of keyword-as-identifier

A new feature in 5.0 is the automatic quoting of identifiers that are believed to be keywords in the underlying database. As this support is new, often the Dialects are too aggressive in what they deem to be keywords. Thus we added a new setting to disable this behavior if it causes problems in your application. This can be controlled by specifying hibernate.auto_quote_keyword as false in configuration settings.

Significantly improved bytecode enhancement support

Including:

  • added ability for automatic management of bi-directional associations

  • self-contained dirty state tracking (more efficient flushing), including switchable algorithms for dirty determination

Odds-n-ends

Additionally many other improvements and bugfixes are included. See the changelogs for the complete list of changes.

The release tag is available on GitHub.

As always, see http://hibernate.org/orm/downloads/ for information on obtaining the releases.

Multitenancy and current session

Posted by Emmanuel Bernard    |       |    Tagged as Hibernate ORM

Today let’s discuss the interaction between multitenancy and the current session feature.

Multitenancy let’s you isolate Session operations between different tenants. This is useful to create a single application isolating different customers from one another.

The current session feature returns the same session for a given context, typically a (JTA) transaction. This facilitates the one session per view/transaction/conversation pattern and avoids the one session per operation anti-pattern.

Session session = sessionFactory.getCurrentSession();
// do some other work
[...]
// later in the same context (e.g. JTA Transaction)
Session session2 = sessionFactory.getCurrentSession();

// semantically we have
assert session == session2

The two features work well together, simply implement CurrentTenantIdentifierResolver. That will give Hibernate ORM the expected tenant id when the current session is created.

How current is current?

When discussing with Florian and the ToulouseJUG, we exchanged on a small case where things might not work as you expect. Hibernate ORM considers that, for a given context (e.g. transaction), there can only be a single current Session.

So if in the same context (e.g. transaction):

  • your CurrentTenantIdentifierResolver implementation returns different values of tenant id,

  • you use getCurrentSession()

you will get a TenantIdentifierMismatchException.

However, it is sometimes useful to be able to reach several tenants from the same context. You have two options:

  • Manually create the Session

  • Implement a custom CurrentSessionContext

Manually create the Session

You can use the SessionFactory API to create a Session for the tenant id you are looking for.

Session session1 = sessionFactory.withOptions()
        .tenantIdentifier( tenant1 )
        ...
        .openSession();
Session session2 = sessionFactory.withOptions()
        .tenantIdentifier( tenant2 )
        ...
        .openSession();

But you have to make sure to close these sessions. If you are used to CDI or Spring handling sessions for you, or if you rely on the current session feature to propagate the session across your stack, this might be annoying.

Implement a custom CurrentSessionContext

The alternative is to implement your own version of CurrentSessionContext, avoid raising the TenantIdentifierMismatchException, and keep Session instances per both context and tenant id.

In practice, current sessions are stored in a ConcurrentHashMap keyed by context identifier, you just need to improve that part. Start with JTASessionContext and hack away!

What now?

We are currently discussing whether the default CurrentSessionContext implementations should partition by tenant id or raise the exception. If you have your opinion, chime in!

In the mean time, use one of the options above.

When creating a bug report for any project within the Hibernate family, it’s extremely helpful (and, frankly, required) to have an adequate test case available. This is obviously important to make reproducing the issue as easy as possible. But it’s also vital longer-term. Nearly every bug fix should include a regression test, which is frequently based on the original reproducer (sometimes, it’s the reproducer, verbatim).

To help create useful test cases, we’re opening up a repo with various templates. Please see the READMEs in each project’s subdir for more info: Hibernate Test Case Templates

As a starting point, the repo contains two templates for ORM:

  • ORMUnitTestCase: By far, this one’s the most helpful. ORM includes a built-in unit test framework that does much of the heavy lifting for you. All that’s required is your entities, logic, and any necessary settings. Since we nearly always include a regression test with bug fixes, providing your reproducer using this method simplifies the process. We can then directly commit it, without having to mold it in first. What’s even better? Fork hibernate-orm itself, add your test case directly to a module’s unit tests (using the template class), then submit it as a PR!

  • ORMStandaloneTestCase: This template is standalone and will look familiar. It simply uses a run-of-the-mill ORM setup. Although it’s perfectly acceptable as a reproducer, lean towards ORMUnitTestCase whenever possible.

The eventual goal is to also include templates for Validator, Search, and OGM.

As always, this is open source for a reason! If the templates can be improved in any way, please let us know (either through our JIRA instance or through GitHub Issues). Better yet, send us a pull request!

For those of you using Hibernate ORM version 5.0.0.CR1, you can now use the freshly released Hibernate Search 5.4 version 5.4.0.Alpha1.

What's new

Absolutely nothing! This Hibernate Search version is identical in terms of features and API to version 5.3.0.CR1: this should make it easier for you all to upgrade the Hibernate ORM libraries (hibernate-core, hibernate-entitymanager,..) without the distraction of changes because of Hibernate Search: focus on the changes you'll need to apply because of the major version upgrade of Hibernate (if any, as it's not too complex at all).

WildFly compatibility and JBoss Modules

With every release of Hibernate Search we normally also release a set of modules to run the latest version of it on WildFly, but in this case since the updated Hibernate ORM 5 integrations for WildFly have yet to be released, we skipped this step. Fear not, the WildFly integration will be finished soon and we'll then resume releasing such module packs as usual. Not least, this very same version of Hibernate Search will soon be available in WildFly 10, so the modules missing today won't actually be needed at all.

This is a great time to try Hibernate 5

While the latest polish is performed on Hibernate 5, we're all looking forward for feedback from you. It is likely that some more changes will be done, but we consider it good enough already to not expect any regression so please try it and let us know! We're at that sweet spot in which you can still propose changes without the chains of strong API compatibility requirements, but good enough for you to not be wasting time on a quickly changing target.

Versions reminder

This version of Hibernate Search requires:

  • Hibernate ORM 5.0.0.CR1
  • Apache Lucene 4.10.x
  • Java SE 7

Our rules and conventions for versions and compatibility are documented here on the GitHub Wiki.

  • Artefact jars are available on Maven Central under the GAV org.hibernate:hibernate-search-orm:5.4.0.Alpha1
  • Zip and tar bundles are available via our website
  • Feedback is welcome on the forums and emails, IRC

Hibernate ORM 5.0.0.CR1 Release

Posted by Steve Ebersole    |       |    Tagged as Hibernate ORM Releases

The Hibernate team is proud to announce the first candidate release for 5.0. The main changes since the Beta2 release include:

  • Initial generic typing for Hibernate native (Session, e.g.) APIs
  • Continued development of the new bytecode enhancement capabilities including improved support in the Maven and Gradle plugins
  • Support for parameterized types with AttributeConverter implementations
  • Improved OSGi integration testing using Pax Exam and Karaf, and publishing a hibernate-osgi Karaf features file
  • Auto quoting of keywords used as identifiers (User, e.g.).
  • Incorporating fixes, improvements and suggestions to the improved schema update and validation tooling

A lot of help from the community went into this release and the previous Beta releases. Thanks for all the help and work and testing and doggedness!

As always, see http://hibernate.org/orm/downloads/ for information on obtaining the releases.

Report any issues to Hibernate Jira

Hibernate ORM 4.3.10.Final Released

Posted by Gail Badner    |       |    Tagged as Hibernate ORM Releases

The primary reason for this release is to add support for running Hibernate ORM with Infinispan 7.2.1.Final as a runtime dependency. Hibernate still uses Infinispan 6.0.0.Final by default.

The plan is for WildFly 9 to include Hibernate ORM 4.3.10.Final. Since WildFly 9 uses Infinispan 7.2.1.Final, we had to make some corrections so that Hibernate ORM works properly with Infinispan 7.2.1.Final (as well as 6.0.0.Final) as a cache provider. To avoid backward-compatibility issues, Hibernate still uses an Infinispan 6.0.0.Final configuration by default.

In order to use Hibernate ORM with Infinispan 7.2.1.Final, it is necessary to specify an Infinispan 7.2 configuration using the environment variable, hibernate.cache.infinispan.cfg. An example of an Infinispan 7.2 configuration has been added as a test resource here.

For more information about changes to support Infinispan 7.2.1.Final, see: HHH-9776 and HHH-9781.

Other changes were minor. For more information, please see: https://hibernate.atlassian.net/jira/secure/ReleaseNote.jspa?projectId=10031&version=19650

JBoss Nexus: https://repository.jboss.org/nexus/content/groups/public/org/hibernate
Maven Central: http://repo1.maven.org/maven2/org/hibernate/hibernate-core (should update in a couple of days)

SourceForge: https://sourceforge.net/projects/hibernate/files/hibernate4
4.3.10.Final Downloads: 4.3.10.Final ZIP, 4.3.10.Final TGZ

Hibernate ORM 5.0.0.Beta2 Release

Posted by Steve Ebersole    |       |    Tagged as Hibernate ORM Releases

I have just finished releasing Hibernate O/RM 5.0.0.Beta2. Beyond Beta1, this release adds:

  1. Support for Spatial/GIS data through importing Hibernate Spatial.
  2. Complete redesign of bulk id tables used to support update/delete queries against multi-table structures. The redesign helps better fit what different databases support.
  3. Redesign of transaction management
  4. Much improved (and still improving!) schema management tooling for export, validation and migration.

At this point, 5.0.0 is getting a lot of testing. So even though it is still in Beta I am feeling pretty confident of its quality. I opted for another Beta here instead of CR1 for a few reasons:

  1. Investigate whether we want to convert Hibernate's native APIs (Session, etc) to be typed. There is one especially tricky case that needs to be figured out. A major release like this would be the time to do that
  2. I have just introduced some pretty significant Transaction changes since Beta1. I felt it would be prudent to have one more Beta to allow people time to try out those changes and allow for additional changes based on feedback
  3. I would still like to complete deprecating the Settings contract. The last piece there is the discussion I started earlier on the dev list wrt its usage in SPI contracts (L2 cache, etc). This effects a few integrations.
  4. I am working on better Karaf support for hibernate-osgi. Specifically creating a Karaf features respository that users can simply pick up and use. That work is well under way, but ongoing.

As always, see http://hibernate.org/orm/downloads/ for information on obtaining Hibernate O/RM.

back to top