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](https://search.maven.org/classic/#search|gav|1|g%3A"org.springframework" AND a%3A"spring-orm") 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](https://search.maven.org/classic/#search|gav|1|g%3A"com.h2database" AND a%3A"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](https://search.maven.org/classic/#search|gav|1|g%3A"org.apache.tomcat" AND a%3A"tomcat-dbcp"), 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:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("sa"); return dataSource;
} @Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
} private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.H2Dialect"); return hibernateProperties;
}
}

4.2. Using XML Configuration

As a secondary option, we can also configure Hibernate 5 with an XML-based configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..."> <bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource"
ref="dataSource"/>
<property name="packagesToScan"
value="com.baeldung.hibernate.bootstrap.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">
create-drop
</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.H2Dialect
</prop>
</props>
</property>
</bean> <bean id="dataSource"
class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:db;DB_CLOSE_DELAY=-1"/>
<property name="username" value="sa"/>
<property name="password" value="sa"/>
</bean> <bean id="txManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

As we can easily see, we’re defining exactly the same beans and parameters as in the Java-based configuration earlier.

To bootstrap the XML into the Spring context, we can use a simple Java configuration file if the application is configured with Java configuration:

@Configuration
@EnableTransactionManagement
@ImportResource({"classpath:hibernate5Configuration.xml"})
public class HibernateXMLConf {
//
}

Alternatively, we can simply provide the XML file to the Spring Context, if the overall configuration is purely XML.

5. Usage

At this point, Hibernate 5 is fully configured with Spring, and we can inject the raw Hibernate SessionFactory directly whenever we need to:

public abstract class BarHibernateDAO {

    @Autowired
private SessionFactory sessionFactory; // ...
}

6. Supported Databases

Unfortunately, the Hibernate project doesn’t exactly provide an official list of supported databases.

That being said, it’s easy to see if a particular database type might be supported, we can have a look at the list of supported dialects.

7. Conclusion

In this quick tutorial, we configured Spring with Hibernate 5 – with both Java and XML configuration.

As always, the full source code of the examples is available over on GitHub.

在spring中使用Hibernate5的更多相关文章

  1. Spring中的事务控制

    Spring中事务控制的API介绍 PlatformTransactionManager 此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法 我们在开发中都是使用它的实现类: 真正 ...

  2. Velocity初探小结--Velocity在spring中的配置和使用

    最近正在做的项目前端使用了Velocity进行View层的数据渲染,之前没有接触过,草草过了一遍,就上手开始写,现在又回头细致的看了一遍,做个笔记. velocity是一种基于java的模板引擎技术, ...

  3. Spring中Bean的作用域、生命周期

                                   Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...

  4. Spring中Bean的实例化

                                    Spring中Bean的实例化 在介绍Bean的三种实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果 ...

  5. 模拟实现Spring中的注解装配

    本文原创,地址为http://www.cnblogs.com/fengzheng/p/5037359.html 在Spring中,XML文件中的bean配置是实现Spring IOC的核心配置文件,在 ...

  6. Spring中常见的bean创建异常

    Spring中常见的bean创建异常 1. 概述     本次我们将讨论在spring中BeanFactory创建bean实例时经常遇到的异常 org.springframework.beans.fa ...

  7. Spring中配置数据源的4种形式

    不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据源配置方式: spring自带的数据源(DriverManagerDataSource),DBCP数据源,C3P0数据源 ...

  8. spring中InitializingBean接口使用理解

    InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会执行该方法. 测试程序如下: imp ...

  9. Quartz 在 Spring 中如何动态配置时间--转

    原文地址:http://www.iteye.com/topic/399980 在项目中有一个需求,需要灵活配置调度任务时间,并能自由启动或停止调度. 有关调度的实现我就第一就想到了Quartz这个开源 ...

随机推荐

  1. Linux C 后台服务程序单进程控制

    介绍 通常后台服务器程序都必须有且只有一个进程,那么如何单进程呢? 本例子是通过flock函数对/var/run/myserver.pid记录pid文件的进行加锁 若加锁不正常,说明后台服务进程已经在 ...

  2. 写css注意的事项

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. Idea中Spring整合MyBatis框架中配置文件中对象注入问题解决方案

    运行环境:Spring框架整合MaBitis框架 问题叙述: 在Spring配置文件applicationContext-mybatis.xml中配置好mybatis之后 <?xml versi ...

  4. spring boot缓存excel临时文件后再操作

    1. 引入poi的两个依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi ...

  5. mac下sourcetree创建git分支和合并分支

    git默认创建的分支为:master主分支 要实现的效果:新建和合并分支. 1.在master基础上创建分支v1.0.1并切换至v1.0.1然后推送分支到远程服务器 确定即可!! 然后查看远端已经发现 ...

  6. HDU 1372 Knight Moves 题解

    Knight Moves Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tota ...

  7. Java精通并发-Condition编程模式详解与分析

    继续上一次https://www.cnblogs.com/webor2006/p/11890688.html的Condition接口说明进行阅读: 上面这个程序会在之后手动来实现一下,说实话这种写法在 ...

  8. LCD编程_使用调色板

    在前面的博客中,使用的像素格式都是16bpp,24bpp(24bpp实际实际上就是32bpp)?如果想使用8bpp时,就需要使用调色板. 在以前的博客中,曾经说过,在framebuffer中如果每个像 ...

  9. 201871010108-高文利《面向对象程序设计(java)》第二周学习总结

    项目 内容 这个作业属于哪个课程 <任课教师博客主页链接>https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 <作业链接地址>http ...

  10. 2019牛客国庆day3-G &CF1238E

    牛客G: 给定大小为N的数组a[],给定M组关系,让你重排a[],使得sum{M队关系的绝对值之差}最小.首先将a排序,然后依次把a填入数组. 假设i在二进制下有x个1,用dp[i]更新dp[i|(1 ...