Bootstrapping Hibernate 5 with Spring – 用Spring对Hibernate 5进行引导

最后修改: 2018年 1月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll discuss how to bootstrap Hibernate 5 with Spring, using both Java and XML configuration.

在这篇文章中,我们将讨论如何使用Java和XML配置,用Spring启动Hibernate 5

This article focuses on Spring MVC. Our article Spring Boot with Hibernate describes how to use Hibernate in Spring Boot.

本文重点介绍Spring MVC。我们的文章使用Hibernate的Spring Boot描述了如何在Spring Boot中使用Hibernate。

2. Spring Integration

2.Spring集成

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).

使用本地 Hibernate API 引导 SessionFactory 有点复杂,需要我们编写相当多的代码(如果你真的需要这样做,请看 官方文档)。

Fortunately, Spring supports bootstrapping the SessionFactoryso that we only need a few lines of Java code or XML configuration.

幸运的是,Spring支持引导SessionFactory因此我们只需要几行Java代码或XML配置。

3. Maven Dependencies

3.Maven的依赖性

Let’s get started by first adding the necessary dependencies to our pom.xml:

让我们开始吧,首先在我们的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:

spring-orm模块提供Spring与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:

为了简单起见,我们将使用H2>作为我们的数据库。

<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:

最后,我们将使用Tomcat JDBC连接池,它比Spring提供的DriverManagerDataSource更适合于生产目的。

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-dbcp</artifactId>
    <version>9.0.1</version>
</dependency>

4. Configuration

4.配置

As mentioned before, Spring supports us with bootstrapping the Hibernate SessionFactory.

如前所述,Spring支持我们引导Hibernate的SessionFactory

All we have to do is to define some beans as well as a few parameters.

我们所要做的就是定义一些Bean以及一些参数

With Spring, we have two options for these configurations, a Java-based and an XML-based way.

有了Spring,我们有两种选择来进行这些配置,一种是基于Java的方式,一种是基于XML的方式。

4.1. Using Java Configuration

4.1.使用Java配置

For using Hibernate 5 with Spring, little has changed since Hibernate 4: we have to use LocalSessionFactoryBean from the package org.springframework.orm.hibernate5 instead of org.springframework.orm.hibernate4.

对于在Spring中使用Hibernate 5,自Hibernate 4以来没有什么变化:我们必须使用org.springframework.orm.hibernate5包中的LocalSessionFactoryBean而不是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.

与之前的Hibernate 4一样,我们必须为LocalSessionFactoryBeanDataSourcePlatformTransactionManager定义bean,以及一些Hibernate特有的属性。

Let’s create our HibernateConfig class to configure Hibernate 5 with Spring:

让我们创建我们的HibernateConfig类来配置Hibernate 5与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

4.2.使用XML配置

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

作为次要选择,我们也可以用基于XML的配置来配置Hibernate 5

<?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.

我们可以很容易地看到,我们所定义的Bean和参数与前面基于Java的配置完全相同。

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

为了将XML引导到Spring上下文中,如果应用程序是用Java配置的,我们可以使用一个简单的Java配置文件。

@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.

另外,如果整体配置是纯粹的XML,我们可以简单地将XML文件提供给Spring Context。

5. Usage

5.使用方法

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

至此,Hibernate 5已经与Spring完全配置好了,我们可以在需要的时候直接注入Hibernate的原始SessionFactory

public abstract class BarHibernateDAO {

    @Autowired
    private SessionFactory sessionFactory;

    // ...
}

6. Supported Databases

6.支持的数据库

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

不幸的是,Hibernate项目并没有完全提供一个支持数据库的官方列表。

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

7.结论

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

在这个快速教程中,我们用Hibernate 5配置了Spring–有Java和XML两种配置。

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

一如既往,这些示例的完整源代码可在GitHub上获得over。