You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot无法找到EntityManagerFactory Bean问题求助

解决Spring Boot启动时找不到EntityManagerFactory的问题

我来帮你梳理下问题所在,你的配置里存在几个重复、冲突以及不符合Spring Boot规范的地方,导致EntityManagerFactory无法被正确创建。咱们一步步来修正:


1. 清理重复且错误的类注解

你的CategoryServiceImpl上同时标注了@Configuration、@ComponentScans和@Service,这完全是错误的用法:

  • @Service是用来标记业务服务类的注解
  • @Configuration是配置类专属注解,不能和业务类注解混用
  • @ComponentScans也不应该出现在服务类上

修改后的CategoryServiceImpl应该是这样:

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    
    // 你的业务方法...
}

2. 修正依赖配置中的循环引用

看你的JPA项目pom.xml,居然引用了自身,这会导致依赖循环问题,直接删掉这段错误的依赖:

<!-- 删掉这段! -->
<dependency>
    <groupId>com.example</groupId>
    <artifactId>spring-hibernate-jpa-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <scope>compile</scope>
</dependency>

然后确保REST控制器项目的pom.xml中,正确引入JPA项目的依赖:

<dependency>
    <groupId>com.example</groupId>
    <artifactId>spring-hibernate-jpa-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

3. 利用Spring Boot自动配置简化配置

你现在手动配置LocalEntityManagerFactoryBean完全没必要,Spring Boot的自动配置可以帮你搞定大部分JPA相关设置:

第一步:添加Spring Boot JPA starter依赖

确保两个项目的pom.xml中都引入这个依赖(如果是REST项目作为启动入口,至少REST项目必须有):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

第二步:简化配置类

删掉AppConfig中的geEntityManagerFactoryBean()方法,同时@EnableTransactionManagement也可以去掉——因为spring-boot-starter-data-jpa已经自动开启了事务管理。

第三步:优化启动类的扫描配置

你的@SpringBootApplication的scanBasePackages不需要包含javax,只需要覆盖你的业务包即可,甚至可以简化成扫描整个com.example包:

@SpringBootApplication(scanBasePackages = "com.example")
@EntityScan("com.example.entity") // 加上这个注解扫描你的JPA实体类
public class Application { }

4. 正确配置数据库连接(推荐用Spring Boot配置文件)

如果你之前用的是persistence.xml,更推荐换成Spring Boot的application.properties或application.yml来配置,更符合Spring Boot的使用习惯。在REST项目的src/main/resources下创建application.properties,添加以下内容:

# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_db_username
spring.datasource.password=your_db_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA/Hibernate配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

如果一定要用persistence.xml,请确保它放在JPA项目的src/main/resources/META-INF目录下,且持久化单元名称和你之前配置的LOCAL_PERSISTENCE一致。


把以上步骤全部修正后,重启你的Spring Boot应用,应该就能解决EntityManagerFactory找不到的问题了。

内容的提问来源于stack exchange,提问作者Geek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:46:49