有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Spring数据ORM/JPA创建EntityManagerFactory?

我正在创建一个独立的Java应用程序,它将Spring数据与JPA结合使用

为EntityManagerFactory创建工厂的类的一部分如下:

@Configuration
@Lazy
public class JpaConfig {

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(MultiTenantConnectionProvider connProvider,  CurrentTenantIdentifierResolver tenantResolver) {
...
}

问题是:我只能在初始化ApplicationContext后检测Hibernate方言,因为这些信息是从外部配置服务读取的

既然@Lazy不起作用,有没有什么策略可以避免在使用这个bean之前创建它,也就是说,只在另一个bean注入EntityManager实例时创建它


共 (1) 个答案

  1. # 1 楼答案

    我最近偶然发现了这个问题,并找到了一个有效的解决方案。不幸的是,“容器”管理的bean将在启动期间初始化,@Lazy被忽略,即使EntityManager没有被注入任何地方

    我通过在启动期间使用内存中的H2 DB构建工厂bean来修复它,并在以后对其进行了更改。我想你可以为你的问题做些什么

    波姆。xml:

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.199</version>
    </dependency>
    

    源代码:

    @Configuration
    public class DataSourceConfig {
    
        @Bean
        public HikariDataSource realDataSource() {
            ...
        }
    
        @Bean
        public DataSource localH2DataSource() {
            return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
        }
    
        @Bean
        public LocalContainerEntityManagerFactoryBean myEntityManagerFactory() throws PropertyVetoException {
            LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
            
            factoryBean.setDataSource(localH2DataSource());
    
            HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
            jpaVendorAdapter.setShowSql(true);
            factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
    
            return factoryBean;
        }
    }
    
    @Component
    @Lazy
    public class Main {
    
        @Autowired
        private LocalContainerEntityManagerFactoryBean emf;
    
        @Autowired
        private HikariDataSource realDataSource;
    
        @PostConstruct
        private void updateHibernateDialect() {
            // read the external config here
            emf.setDataSource(realDataSource);
            
            Properties jpaProperties = new Properties();
            jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.DB2Dialect");
            factoryBean.setJpaProperties(jpaProperties);
        }
    }