Hibernate with Java 8

Somewhere last year I had this crazy idea – how awesome it would be to have combined Hibernate together with latest Java 8 release: handling null objects with Optional, processing Hibernate Queries through streams operating on LocalDate, LocalTime. All of those features used together to refresh the existing API and give the new kind of look and feel.

Due to different reasons this is quite unlikely to happen in Hibernate Core in near future (Hibernate 5 will be remain Java 6 backward compatibility), so untill Hibernate will have such native support it’s possible to use wrappers on top of Hibernate like for instance Spring Data JPA. Although if you tied up to plain old Hibernate there is another option. A small extension that I had build on top of Hibernate Query API that I’ve called HStreams.

At the moment it gives you set of features:

  • Typed queries
  • Query Stream results
  • Optional entity results

Additional documentation and details: https://github.com/jmnarloch/hstreams/blob/hstreams-43/api.adoc

Sneak peak:

SessionFactory originalFactory = ...;

StreamSessionFactory factory = Streams.wrap(originalFactory);
StreamSession session = factory.getCurrentSession();

long count = session.createQuery("from User")
        .stream()
        .count();

Optional<User> admin = session.createTypedQuery("from User where id = :id", User.class)
        .setParameter("id", 1l)
        .stream()
        .findFirst();

Optional<User> user = session.getOptional("User", 1l);

So if you want to get some benefits of Java 8 and you use plain Hibernate in your project you can just grab the wrapper from maven central and have fun.

3 comments

  1. Pingback: Hibernate 5 with Java 8 | I just do things
  2. Sedfrey · March 23

    I just have a question. Can hibernate 2 work with Java 8?

    Like

    • Jakub Narloch · June 15

      In general probably yes, you should be able to run the Hibernate in JDK 8.

      Although if you want to use of any of this features then the answer is no, sorry. The extension was targeted only to specific versions of Hibernate. Although at the moment you can consider it obsolete, since Hibernate 5.2 has been released, which has similar functionality.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s