Spring Boot JPA findAll查询返回空结果问题求助
问题分析与解决方案
核心问题原因
- DDL自动生成策略冲突:你配置了
spring.jpa.hibernate.ddl-auto=create-drop,Hibernate会在应用启动时根据Entity自动创建新表,停止时删除该表。而你手动创建的CUSTOMER_ACCOUNT表和Hibernate生成的表并非同一个,导致查询的是空表。 - 表名大小写映射问题:Docker中的MariaDb默认可能启用表名小写转换,即便设置了
globally_quoted_identifiers=true,Hibernate仍生成小写customer_account表,和你手动创建的大写表不匹配。 - Repository查询错误:自定义的
findAllCA()查询返回的是三个字段的元组,而非CustomerAccountEntity对象,无法正确映射为实体列表。 - 主键类型不匹配:Repository定义的主键类型是
Long,但实体类的accountId是int类型,类型不匹配会引发查询异常。 - 驱动兼容性问题:使用CData驱动而非官方MariaDb驱动,可能存在适配问题。
分步解决方法
1. 调整DDL自动生成策略
修改application.properties,关闭Hibernate自动创建/删除表的功能(你已手动创建表):
spring.jpa.hibernate.ddl-auto=none
若需要Hibernate验证实体与表结构一致性,可改为validate。
2. 确保表名正确映射
- 启动Docker MariaDb容器时添加参数
--lower_case_table_names=0(开启表名大小写区分),保证大写表名能被识别。 - 调整Entity类的
@Table注解,移除多余的catalog属性:
@Entity @Table(name = "CUSTOMER_ACCOUNT", schema = "dev") public class CustomerAccountEntity { // ... 原有代码 }
3. 修复Repository查询
删除自定义的findAllCA()方法,直接使用JpaRepository自带的findAll();若需自定义查询,需返回实体对象:
@Repository public interface CustomerAccountRepository extends JpaRepository<CustomerAccountEntity, Integer> { // 自定义查询写法 @Query("SELECT ca FROM CustomerAccountEntity ca") List<CustomerAccountEntity> findAllCA(); }
4. 修正主键类型
Repository泛型的主键类型需与实体类accountId类型一致(实体类为int,对应包装类Integer):
public interface CustomerAccountRepository extends JpaRepository<CustomerAccountEntity, Integer> { // ... }
5. 使用官方MariaDb驱动
替换驱动配置为官方版本,Spring Boot可自动识别,也可显式指定:
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
或直接删除驱动配置,Spring Boot会根据jdbc:mariadb://前缀自动加载正确驱动。
验证步骤
- 重启Spring Boot应用,确认MariaDb中不再生成新的
customer_account表。 - 调用控制器接口,检查返回结果是否为你手动插入的18条数据。
内容的提问来源于stack exchange,提问作者stana
相关产品推荐
相关产品推荐

