SpringBoot测试报错:创建entityManagerFactory Bean失败求助
CamelCaseToUnderscoresNamingStrategy类找不到的解决思路 问题描述
运行SpringBoot应用的JUnit测试时抛出以下错误:
java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy Caused by: java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy Caused by: java.lang.ClassNotFoundException: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy
环境:Java 11、Spring Boot 2.6.7
已执行操作:
- 添加
spring-boot-starter-data-jpa依赖(排除了logging模块) - 移除手动添加的固定版本
hibernate-core和hibernate-entitymanager(5.5.0.Final) - 提供了合并父工程与子工程后的完整pom.xml
核心原因
CamelCaseToUnderscoresNamingStrategy是Hibernate 5.6及以上版本才引入的类,Spring Boot 2.6.7默认适配的Hibernate版本为5.6.10.Final。但你的pom.xml中仍保留了手动引入的无版本号hibernate-core和hibernate-entitymanager,可能导致Maven依赖解析时拉取了不兼容的低版本Hibernate,或依赖冲突让正确版本的类无法加载。
解决步骤
删除所有手动引入的Hibernate依赖
立即移除pom.xml中以下两个依赖:<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> </dependency>spring-boot-starter-data-jpa已自动包含适配当前Spring Boot版本的Hibernate依赖,手动引入会破坏Spring的依赖管理机制。清理重复的测试依赖
pom.xml中重复声明了spring-boot-starter-test、junit-jupiter-engine、junit-jupiter-api、openpojo等测试依赖,这会引发依赖冲突或版本不一致问题。保留一组完整的spring-boot-starter-test即可,它已包含JUnit 5相关依赖,无需单独声明junit-jupiter-engine和junit-jupiter-api。执行Maven依赖清理与更新
运行命令清理本地仓库中可能损坏或冲突的依赖,并强制拉取最新的适配版本:mvn clean install -U验证Hibernate依赖版本
运行命令查看实际引入的Hibernate版本,确认是否为5.6.x:mvn dependency:tree | grep hibernate-core如果版本不是5.6.x,说明其他依赖引入了低版本Hibernate,需找到对应依赖并排除。
检查配置文件的命名策略
如果application.properties或application.yml中手动配置了spring.jpa.hibernate.naming.physical-strategy,确认拼写为org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy。Spring Boot 2.6.x默认使用该策略,通常无需手动配置。
内容的提问来源于stack exchange,提问作者Bagira

