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:

  1. <dependency>
  2. <groupId>org.hibernate</groupId>
  3. <artifactId>hibernate-core</artifactId>
  4. <version>5.4.2.Final</version>
  5. </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:

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-orm</artifactId>
  4. <version>5.1.6.RELEASE</version>
  5. </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:

  1. <dependency>
  2. <groupId>com.h2database</groupId>
  3. <artifactId>h2</artifactId>
  4. <version>1.4.197</version>
  5. </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:

  1. <dependency>
  2. <groupId>org.apache.tomcat</groupId>
  3. <artifactId>tomcat-dbcp</artifactId>
  4. <version>9.0.1</version>
  5. </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:

  1. @Configuration
  2. @EnableTransactionManagement
  3. public class HibernateConf {
  4. @Bean
  5. public LocalSessionFactoryBean sessionFactory() {
  6. LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
  7. sessionFactory.setDataSource(dataSource());
  8. sessionFactory.setPackagesToScan(
  9. {"com.baeldung.hibernate.bootstrap.model" });
  10. sessionFactory.setHibernateProperties(hibernateProperties());
  11. return sessionFactory;
  12. }
  13. @Bean
  14. public DataSource dataSource() {
  15. BasicDataSource dataSource = new BasicDataSource();
  16. dataSource.setDriverClassName("org.h2.Driver");
  17. dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
  18. dataSource.setUsername("sa");
  19. dataSource.setPassword("sa");
  20. return dataSource;
  21. }
  22. @Bean
  23. public PlatformTransactionManager hibernateTransactionManager() {
  24. HibernateTransactionManager transactionManager
  25. = new HibernateTransactionManager();
  26. transactionManager.setSessionFactory(sessionFactory().getObject());
  27. return transactionManager;
  28. }
  29. private final Properties hibernateProperties() {
  30. Properties hibernateProperties = new Properties();
  31. hibernateProperties.setProperty(
  32. "hibernate.hbm2ddl.auto", "create-drop");
  33. hibernateProperties.setProperty(
  34. "hibernate.dialect", "org.hibernate.dialect.H2Dialect");
  35. return hibernateProperties;
  36. }
  37. }

4.2. Using XML Configuration

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

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="...">
  3. <bean id="sessionFactory"
  4. class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  5. <property name="dataSource"
  6. ref="dataSource"/>
  7. <property name="packagesToScan"
  8. value="com.baeldung.hibernate.bootstrap.model"/>
  9. <property name="hibernateProperties">
  10. <props>
  11. <prop key="hibernate.hbm2ddl.auto">
  12. create-drop
  13. </prop>
  14. <prop key="hibernate.dialect">
  15. org.hibernate.dialect.H2Dialect
  16. </prop>
  17. </props>
  18. </property>
  19. </bean>
  20. <bean id="dataSource"
  21. class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
  22. <property name="driverClassName" value="org.h2.Driver"/>
  23. <property name="url" value="jdbc:h2:mem:db;DB_CLOSE_DELAY=-1"/>
  24. <property name="username" value="sa"/>
  25. <property name="password" value="sa"/>
  26. </bean>
  27. <bean id="txManager"
  28. class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  29. <property name="sessionFactory" ref="sessionFactory"/>
  30. </bean>
  31. </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:

  1. @Configuration
  2. @EnableTransactionManagement
  3. @ImportResource({"classpath:hibernate5Configuration.xml"})
  4. public class HibernateXMLConf {
  5. //
  6. }

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:

  1. public abstract class BarHibernateDAO {
  2. @Autowired
  3. private SessionFactory sessionFactory;
  4. // ...
  5. }

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 集群概念 , wsgi , Nginx负载均衡实验 , 部署CRM(Django+uwsgi+nginx), 部署学城项目(vue+uwsgi+nginx)

    Linux 集群概念 , wsgi , Nginx负载均衡实验 , 部署CRM(Django+uwsgi+nginx), 部署学城项目(vue+uwsgi+nginx) 一丶集群和Nginx反向代理 ...

  2. linux sed、awk、grep同时匹配多个条(并且 or 或者)

    同时匹配ABC 和 abc: sed -n '/ABC/{/abc/p}' awk '/ABC/&&/abc/{ print $0 }' grep -E '(ABC.*abc|abc. ...

  3. iis url 重写

    1.选择网站-找到有测url 重写 :2:选中它,在右上角有一个打开功能,点击打开 3.依然在右上角,点击添加规则 4:选择第一个,空白规则 名称随便输入,我们通常有这样一个需求,就是.aspx 后缀 ...

  4. idea2019注册码

    都9012年了,怎么还能忍受用低版本的编辑器呢, IntelliJ IDEA 2019破解教程拿走不谢 下载工具 Mac版idea下载链接: 链接:https://pan.baidu.com/s/1m ...

  5. 【夯实基础】-浅谈"单点登录"的几种实现方式

    单点登录 一.Session跨域 所谓Session跨域就是摒弃了系统提供的Session,而使用自定义的类似Session的机制来保存客户端数据的一种解决方案. 如:通过设置cookie的domai ...

  6. 中国工业的下一个十年在哪里?APS系统或将引领智能化转型

    为什么众多的ERP软件公司没有推出相关产品,当然可以肯定的是并非客户没有此观念,如果一定要说,也只能说目前的需求还不是非常强烈,从ERP厂商非常急切的与APS公司合作,甚至有高价购买APS公司代码的情 ...

  7. SqlServer数据库优化之索引、临时表

    问题:工作是查询一张500万多条数据的表时,查询总是很慢,于是进行优化. --查询表所有索引 use RYTreasureDB EXEC Sp_helpindex [RecordDrawScore] ...

  8. C++ OpenSSL 之二:生成RSA文件

    1.等同于生成private key: openssl genrsa -out "save_path" 2048 2.代码如下 bool MakeRsaKeySSL(const c ...

  9. Linux shell sed命令使用

    Linux处理文本文件的工具:     grep        过滤文件内容     sed            编辑文件内容     awk             正则表达式Regex      ...

  10. 简单理解EM算法Expectation Maximization

    1.EM算法概念 EM 算法,全称 Expectation Maximization Algorithm.期望最大算法是一种迭代算法,用于含有隐变量(Hidden Variable)的概率参数模型的最 ...