在spring中使用Hibernate5
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的更多相关文章
- Spring中的事务控制
Spring中事务控制的API介绍 PlatformTransactionManager 此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法 我们在开发中都是使用它的实现类: 真正 ...
- Velocity初探小结--Velocity在spring中的配置和使用
最近正在做的项目前端使用了Velocity进行View层的数据渲染,之前没有接触过,草草过了一遍,就上手开始写,现在又回头细致的看了一遍,做个笔记. velocity是一种基于java的模板引擎技术, ...
- Spring中Bean的作用域、生命周期
Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...
- Spring中Bean的实例化
Spring中Bean的实例化 在介绍Bean的三种实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果 ...
- 模拟实现Spring中的注解装配
本文原创,地址为http://www.cnblogs.com/fengzheng/p/5037359.html 在Spring中,XML文件中的bean配置是实现Spring IOC的核心配置文件,在 ...
- Spring中常见的bean创建异常
Spring中常见的bean创建异常 1. 概述 本次我们将讨论在spring中BeanFactory创建bean实例时经常遇到的异常 org.springframework.beans.fa ...
- Spring中配置数据源的4种形式
不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据源配置方式: spring自带的数据源(DriverManagerDataSource),DBCP数据源,C3P0数据源 ...
- spring中InitializingBean接口使用理解
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会执行该方法. 测试程序如下: imp ...
- Quartz 在 Spring 中如何动态配置时间--转
原文地址:http://www.iteye.com/topic/399980 在项目中有一个需求,需要灵活配置调度任务时间,并能自由启动或停止调度. 有关调度的实现我就第一就想到了Quartz这个开源 ...
随机推荐
- springmvc之静态资源访问不到 -记一次惨痛的经历
springmvc之静态资源访问不到 -记一次惨痛的经历 问题描述:项目正常启动,可以访问页面,但是无法找到静态资源文件,如css,js等文件资源. 控制台: $ 未定义 页面: GET http:/ ...
- js数组去重 数组拼接 替换数组中的指定值 递归数组 判断数组中是否存在指定值 数组求和 根据条件判数组值
这是学习过程中记录的一些关于数组操作的常用属性或方法,记录一下方便以后使用. // 数组去重 var arr1 = [1,1,2,3,4,5,6,3,2,4,5,'a','b','c','a',6,7 ...
- Java生成前三位是字母循环的字典
title: Java生成前三位是字母循环的字典 date: 2018-08-17 18:52:22 tags: Java --- 最近要破解一个秘密,还好这个密码是有线索的,已知密码的前三位是三个字 ...
- FPM十:FORM Repeater
1.创建feeder class:ZCL_FPM_FORM_REP_DEMO 添加接口类: 2.新建全局内表: DATA:GT_QPGT TYPE TABLE OF QPGT. 3.实列化get_da ...
- flask项目结构
project/ app/ # 整个程序的包目录 static/ # 静态资源文件 js/ # JS脚本 css/ # 样式表 img/ # 图片 favicon.ico # 网站图标 templat ...
- MySQL Execution Plan--合理利用隐式的业务逻辑
问题描述 优化过程中遇到一个SQL: SELECT SUM(user_value) FROM user_log ; 其执行计划为: . row *************************** ...
- 05. redis事务
目录 Redis 事务 事务 1. 命令有序 2. 始终原子 开启使用事务 Redis事务中出现错误 1. EXEC前的错误 2. EXEC后的错误 为什么出错了不支持roll backs? Redi ...
- CPU使用率与负载的爱恨情仇
今天有一个电话面试,面试官问我:CentOS怎么查看CPU负载?我说:看top的第一行有load average.面试官又问:为什么从这就判定是负载高呢?依据是什么呢?然后... 然后我就尴尬了,挂了 ...
- Java错误体系
1.Java所有的异常错误都继承与Throwable类,只有继承了Throwable类,才能在异常传递体系中进行. 2.Throwable下有两个重要的子类,Error和Exception Error ...
- 11-cmake语法-函数和宏的定义
cmake语法不仅仅可以适用于 CMakeLists.txt,也适用于 xxx.cmake 文档. 在 OpenCV 的 CMakeLists.txt 中,很多 ocv_XXX() 的函数,都是定义在 ...