hibernate - 关于 EntityManagerFactory 和 SessionFactory 与 Hibernate 5.3、Spring Data JPA 2.1.4 和 Spring 5.1 的混淆

标签 hibernate spring-data-jpa spring-data hibernate-5.x hibernate-5

我试图找出集成 Hibernate 和 Spring Data JPA 的新机制。我遵循了 https://www.baeldung.com/hibernate-5-spring 上提供的示例但无济于事。 进一步的研究给我带来了issue on Github Juergen Hoeller 说:

[...] This covers a lot of ground for a start: With Hibernate 5.2 and 5.3, LocalSessionFactoryBean and HibernateTransactionManager serve as a 99%-compatible replacement for LocalContainerEntityManagerFactoryBean and JpaTransactionManager in many scenarios, allowing for interaction with SessionFactory.getCurrentSession() (and also HibernateTemplate) next to @PersistenceContext EntityManager interaction within the same local transaction (#21454). That aside, such a setup also provides stronger Hibernate integration (#21494, #20852) and more configuration flexibility, not being constrained by JPA bootstrap contracts.

以及 LocalSessionFactoryBean 对应的 Javadoc类说明:

Compatible with Hibernate 5.0/5.1 as well as 5.2/5.3, as of Spring 5.1. Set up with Hibernate 5.3, LocalSessionFactoryBean is an immediate alternative to LocalContainerEntityManagerFactoryBean for common JPA purposes: In particular with Hibernate 5.3, the Hibernate SessionFactory will natively expose the JPA EntityManagerFactory interface as well, and Hibernate BeanContainer integration will be registered out of the box. In combination with HibernateTransactionManager, this naturally allows for mixing JPA access code with native Hibernate access code within the same transaction.

我用 Spring Boot 2.1.2.RELEASE 实现了一个简单的示例项目。它提供了一个简单的配置(与上面的 Baeldung 示例相同)并连接到 PostgreSQL 数据库。此外,从理论上讲,它使用模型和存储库来处理数据。这些类看起来像这样:

DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication
{

    public static void main(String[] args)
    {
        SpringApplication.run(DemoApplication.class, args);
    }
}

基本配置.java

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.config.BootstrapMode;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import org.postgresql.Driver;
import java.util.Properties;

@Configuration
@EnableJpaRepositories
public class BasicConfig
{
    @Bean
    public LocalSessionFactoryBean sessionFactory()
    {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan("com.example.demo");
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public DataSource dataSource()
    {
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass(Driver.class);
        dataSource.setUrl("jdbc:postgresql://localhost:5432/backend");
        dataSource.setUsername("backend");
        dataSource.setPassword("backend");

        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.PostgreSQL95Dialect");

        return hibernateProperties;
    }
}

模型.java

package com.example.demo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "model")
public class Model
{
    @Id
    @GeneratedValue
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @Column(name = "name")
    private String name;
}

DemoRepository.java

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface DemoRepository extends JpaRepository<Model, Long>
{
}

一旦我添加了 DemoRepository 应用程序就不再启动,因为:

A component required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

完整的错误信息:

Exception encountered during context initialization - cancelling refresh
attempt: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'demoRepository': 
Cannot create inner bean '(inner bean)#6c5ca0b6' of type  [org.springframework.orm.jpa.SharedEntityManagerCreator]  
while setting bean property 'entityManager';  
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name '(inner bean)#6c5ca0b6': 
Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No bean named 'entityManagerFactory' available

我的印象是 SessionFactory 现在正确地实现并公开了 EntityManagerFactory 但事实似乎并非如此。我很确定我的实现中存在缺陷,并且 Baeldung 中的示例确实可以正常工作。我希望有人能指出我的错误并帮助我理解我的错误。
提前感谢大家。

依赖关系:

  • spring-data-jpa:2.1.4.RELEASE
  • spring-core:5.1.4.RELEASE
  • spring-orm:5.1.4.RELEASE
  • hibernate 核心:5.3.7.Final
  • spring-boot:2.1.2.RELEASE

gradle.build

buildscript {
    ext {
        springBootVersion = '2.1.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.postgresql:postgresql'
}

最佳答案

经过反复试验,我们发现配置有什么问题。以下(删节)配置有效:

@Configuration
@EnableJpaRepositories(
        basePackages = "com.example.repository",
        bootstrapMode = BootstrapMode.DEFERRED
)
@EnableTransactionManagement
@Profile({ "local", "dev", "prod" })
public class DatabaseConfig
{
    @Bean
    public LocalSessionFactoryBean entityFactoryBean(
            final DataSource dataSource
    )
    {
        final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPackagesToScan("com.example.model");

        return sessionFactory;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
    {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Bean
    public HibernateTransactionManager transactionManager(
            final SessionFactory sessionFactory,
            final DataSource dataSource
    )
    {
        final HibernateTransactionManager transactionManager = new HibernateTransactionManager();

        transactionManager.setSessionFactory(sessionFactory);
        transactionManager.setDataSource(dataSource);

        return transactionManager;
    }
}

LocalSessionFactoryBean 可以命名为 entityFactoryBean,Spring 仍然能够为 hibernateTransactionManager Autowiring 一个 SessionFactoy。 如果其他人遇到类似问题,我希望这对您有所帮助。

关于hibernate - 关于 EntityManagerFactory 和 SessionFactory 与 Hibernate 5.3、Spring Data JPA 2.1.4 和 Spring 5.1 的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276030/

相关文章:

oracle - 使用 Spring Data Jpa 调用 Oracle 中的存储过程时参数的数量或类型错误

java - 使用注释的 Hibernate 一对多映射;我正在尝试使用外键关联将用户 ID 保存在另一个表中。

java - 是否可以让 Hibernate 忽略架构验证列类型不匹配错误

java - Spring Boot 3 JPA 规范未使用 jakarta 进行过滤

java - Spring Data 和 MongoDB 存储库 - 如何创建更新查询?

Spring Data Rest - 按嵌套属性排序

java - Spring 通用 Hibernate DAO

java - 带有 SQL 日期的 DateField Vaadin 组件

java - 如何通过 spring-data 为 @ManyToMany 加载获取选择?

hibernate - 从 grails 域的属性中获取数据库列名