目录
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:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.2.Final</version>
</dependency>
The spring-orm module provides the Spring integration with Hibernate:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
For the sake of simplicity, we’ll use H2 as our database:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
Finally, we are going to use Tomcat JDBC Connection Pooling, which fits better for production purposes than the DriverManagerDataSource provided by Spring:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>9.0.1</version>
</dependency>
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 LocalSessionFactoryBeanfrom 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.
Let’s create our HibernateConfig class to configure Hibernate 5 with Spring:
@Configuration
@EnableTransactionManagement
public class HibernateConf {
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(
{"com.baeldung.hibernate.bootstrap.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc