SpringBoot多数据源配置报错:EntityManagerFactoryBuilder无dataSource方法
问题解决:EntityManagerFactoryBuilder无dataSource方法报错
错误根源
你导入的EntityManagerFactoryBuilder是Hibernate提供的org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder,这个类并没有dataSource()方法。正确的应该使用Spring Boot封装的org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder,它才包含配置数据源的相关方法。
修正步骤
替换导入类
删除Hibernate的Builder导入:import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;替换为Spring Boot的Builder:
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;修正代码中的笔误
代码里存在多处包名拼写错误:com.examle.demo.config.h2db→ 应为com.example.demo.config.h2dbbasePackages = { "package com.example.h2db.repo" }→ 多余package前缀,应为"com.example.h2db.repo"com.eaxample.demo.model.h2db→ 应为com.example.demo.model.h2db
(可选)添加JPA属性配置
如果需要配置Hibernate的方言、DDL策略等,可以恢复并完善HashMap配置。
修正后的完整代码
package com.example.demo.config.h2db; import java.util.HashMap; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "db1EntityManagerFactory", transactionManagerRef = "db1TransactionManager", basePackages = { "com.example.h2db.repo" } ) public class DbOneConfig { @Bean @ConfigurationProperties(prefix = "db1.datasource") public DataSource db1DataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "db1EntityManagerFactory") public LocalContainerEntityManagerFactoryBean db1EntityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("db1DataSource") DataSource db1DataSource ) { HashMap<String, Object> properties = new HashMap<>(); properties.put("hibernate.hbm2ddl.auto", "update"); properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); return builder .dataSource(db1DataSource) .packages("com.example.demo.model.h2db") .properties(properties) .build(); } @Bean public PlatformTransactionManager db1TransactionManager( @Qualifier("db1EntityManagerFactory") EntityManagerFactory entityManagerFactory ) { return new JpaTransactionManager(entityManagerFactory); } }
内容的提问来源于stack exchange,提问作者pooja b
相关产品推荐
相关产品推荐

