文档章节

在spring中使用Hibernate5

物种起源-达尔文
 物种起源-达尔文
发布于 2019/09/02 10:09
字数 752
阅读 74
收藏 0

[TOC]

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.

© 著作权归作者所有

物种起源-达尔文

物种起源-达尔文

粉丝 5
博文 110
码字总数 172969
作品 0
深圳
程序员
私信 提问
加载中

评论(0)

J2Cache 新增 Hibernate 5 支持,感谢 @tandy 贡献

想了解 J2Cache 是一个什么开源项目,请阅读 这篇博客。 J2Cache 刚新增对 Hibernate 5 的支持,提供了 j2cache-hibernate5 模块,可以方便在 Hibernate 5 中启用 J2Cache 缓存。 该模块由 ...

红薯
2018/09/28
1.3K
10
Spring4+SpringMVC+Hibernate4整合,你可能会遇到的问题

1、java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.LocalSessionFactoryBean 缺少spring-orm jar包,如下: <dependency> <groupId>org.springframework</groupId> ......

阿阿阿阿阿局
2016/08/16
160
0
中式流程引擎 UFLO 发布 2.0.4 正式版

中式流程引擎UFLO发2.0.4正式版发布了,更新如下: 在默认的Hibernate5版本中,将依赖的Hibernate版本从5.2.11.Final降为5.1.10.Final以解决运行时控制台出现的Hibernate警告信息 将保存以及...

youseries
2017/10/30
1.9K
3
Spring4 hibernate5整合 事务管理问题

applicationContext.xml: DaoImpl: package com.company.SH.dao.Impl; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.ann......

rickbpoy
2017/05/31
498
4
Spring Framework 4.3.2 和 5.0.0.M1 发布

Spring Framework 4.3.2 和 5.0.0.M1 发布了,详情:Change Log Spring Framework 4.3.2 更新如下: Bug [SPR-10343] - ConfigurationClassParser needs to load annotations through sourc......

淡漠悠然
2016/07/29
8.4K
22

没有更多内容

加载失败,请刷新页面

加载更多

单利模式

花乐天
19分钟前
35
0
生成ssh_key

#生成包含mail的sshkeyssh-keygen -t rsa -C "your_email@example.com"#文件存放路径和文件名Enter file in which to save the key (/Users/teddy/.ssh/id_rsa): /Users/teddy/.ssh/id_r......

人中泰迪
19分钟前
53
0
代理模式

代理模式(Proxy Pattern)是只为其他对象提供一种代理,以控制对这个对象的访问,属于结构行模式。 代理模式一般包含三种角色: 抽象主题角色:抽象主题类的主要职责是声明真实主题与代理的...

xjkvkv
22分钟前
42
0
SQLPro for MySQL for Mac(SQL数据库管理工具) v1.0.315

sqlpro for mysql mac是一款运行在Mac OS平台上的SQL数据库管理工具,轻量级但功能强大的数据库mysql客户端,允许快速和简单的访问MySQL服务器,包括那些驻留在Amazon RDS,方便和快速的连接到...

麦克W
23分钟前
36
0
文件处理及分区管理

{6.shell脚本命令} [1.diff] diff file file1 **比较两个文件的不同 -c **显示周围的行 -u **按照一格式统一输出生成补丁 -r **比较两个目录中文件的不同 patch file file.patch **打补丁 -b...

osc_5ijle82k
30分钟前
47
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部