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

Spring Boot启动报错Hibernate SessionFactory配置找不到问题求助

问题排查及修复方案

1. 配置类未被Spring扫描加载

启动类StudentsApplication的@ComponentScan仅配置了model、controller、dao、service四个包路径,你的DbConfig配置类不在上述包范围内,导致Spring无法加载该配置类,其中定义的SessionFactory相关Bean自然无法被识别。
修复方法:
将DbConfig所在包路径添加到@ComponentScan扫描范围中,若DbConfig在启动类所在根包下也可以直接删除自定义的@ComponentScan注解,Spring Boot默认会扫描启动类所在包及所有子包。

// 修改后示例
@ComponentScan({"model", "controller", "dao", "service", "你的DbConfig所在包名"})

2. DataSource配置键不匹配

DbConfig中读取数据源配置使用的键是jdbc.driverClassName、jdbc.url等,但application.properties中配置的是spring.datasource.url、spring.datasource.username等,键名不匹配会导致DataSource初始化失败,进而影响SessionFactory创建。
修复方法:
统一修改DbConfig的读取键即可:

dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(environment.getProperty("spring.datasource.url"));
dataSource.setUsername(environment.getProperty("spring.datasource.username"));
dataSource.setPassword(environment.getProperty("spring.datasource.password"));

同时记得在application.properties中补充MySQL驱动类配置:spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver(根据你的MySQL版本选择对应驱动类)。

3. SessionFactory类型暴露问题

你在DbConfig中定义的LocalSessionFactoryBean是FactoryBean类型,Spring默认不会自动将其转换为SessionFactory类型供注入,需要显式暴露SessionFactory Bean。
修复方法:
在DbConfig中新增如下Bean定义:

@Bean
public SessionFactory sessionFactory() {
    return getSessionFactory().getObject();
}

4. 实体扫描路径不统一

DbConfig中配置的实体扫描路径是com.alpheus.students.entity,但启动类扫描的实体包是model,如果你的Student实体类在model包下,需要修改实体扫描路径:

factoryBean.setPackagesToScan("model");

5. HQL语法错误

DAO类中的HQL写法存在语法错误,from student where = id需要修改为合法格式:

// 查询单条修改为
TypedQuery<Student> q = sessionFactory.getCurrentSession().createQuery("from Student where id = :id", Student.class)
    .setParameter("id", id);
// 删除语句修改为
sessionFactory.getCurrentSession().createQuery("delete from Student where id = :id")
    .setParameter("id", id)
    .executeUpdate();

注意HQL中写的是实体类名(首字母大写的Student)不是数据库表名,参数占位符需要写成:参数名格式。

6. 依赖检查

确认你的pom.xml或build.gradle中已经引入了spring-orm、hibernate-core以及MySQL驱动的相关依赖,缺失依赖也会导致SessionFactory初始化失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:00:02