I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Overview

In this article, we'll discuss how to bootstrap Hibernate 5 with Spring, using both Java and XML configuration.

2. Spring Integration

Bootstrapping a SessionFactory with the native Hibernate API is a bit complicated and would take us quite a few lines of code (have a look at the official documentation in case you really need to do that).

Fortunately, Spring supports bootstrapping the SessionFactory – so that we only need a few lines of Java code or XML configuration.

Also, before we jump in, if you're working with older versions of Hibernate, you can have a look at the articles about Hibernate 3 as well as Hibernate 4 with Spring.

3. Maven Dependencies

Let's get started by first adding the necessary dependencies to our pom.xml:

4. Configuration

As mentioned before, Spring supports us with bootstrapping the Hibernate SessionFactory.

All we have to do is to define some beans as well as a few parameters.

With Spring, we have two options for these configurations, a Java-based and an XML-based way.

4.1. Using Java Configuration

For using Hibernate 5 with Spring, little has changed since Hibernate 4: we have to use LocalSessionFactoryBean from the package org.springframework.orm.hibernate5 instead of org.springframework.orm.hibernate4.

Like with Hibernate 4 before, we have to define beans for LocalSessionFactoryBean, DataSource, and PlatformTransactionManager, as well as some Hibernate-specific properties.