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

GraphQL查询返回null问题求助(Spring+H2环境)

希思罗航班离港GraphQL API返回Null排查清单

1. 先确认H2数据库数据是否真的存在

  • 启动应用后打开H2控制台(默认地址http://localhost:8080/h2-console),用配置里的JDBC URL登录
  • 执行SQL:SELECT * FROM FLIGHT_DEPARTURE;,查看import.sql里的模拟数据有没有入库
  • 注意:Spring Boot仅在内嵌数据库+首次启动+无预存数据文件时才会执行import.sql,如果之前启动过生成了testdb.mv.db这类文件,会跳过执行,删掉文件再重启即可

2. 实体类与数据库映射检查

  • 确认@Entity类的@Table(name="FLIGHT_DEPARTURE")和SQL里的表名完全一致(大小写敏感)
  • 主键字段必须加@Id注解,否则JPA无法识别主键,查询会返回空
  • 每个字段的@Column注解要匹配数据库字段名,比如数据库里的FLIGHT_NUMBER对应实体类的@Column(name="FLIGHT_NUMBER"),别写错大小写

3. Resolver与Repository逻辑检查

  • 确认Repository接口正确继承JpaRepository<FlightDeparture, 主键类型>,比如JpaRepository<FlightDeparture, Long>
  • 在Resolver方法里加日志或打印语句,直接输出Repository查询结果(比如System.out.println(flightRepo.findAll())),确认是数据库查不到还是Resolver没返回
  • 检查Resolver方法名和Schema查询字段名匹配:比如Schema定义getAllFlights: [Flight],Resolver方法要叫getAllFlights(),或者用@QueryMapping(name="getAllFlights")显式指定

4. GraphQL Schema定义检查

  • 确认Schema里的Flight类型字段和实体类字段完全匹配(大小写敏感),比如Schema里写flightNumber,实体类也得是flightNumber,不能写成flightnumber
  • 确认Schema文件放在src/main/resources/graphql/schema.graphqls,或者在application.properties里配置spring.graphql.schema.locations指定路径,否则Spring无法扫描到
  • 检查查询语句的正确性,比如不要漏写字段,或者查询未定义的字段

5. Spring配置文件检查

  • 确认H2核心配置正确,示例:
    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.driver-class-name=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.jpa.hibernate.ddl-auto=create-drop
    spring.h2.console.enabled=true
    
  • 开启GraphiQL方便测试:spring.graphql.graphiql.enabled=true
  • 注意:spring.jpa.hibernate.ddl-auto如果设为update,可能不会重建表结构,导致import.sql的数据插不进去,改成create-drop更适合测试场景

6. 直接测试Repository

  • 写个测试类,注入Repository直接调用查询方法,比如:
    @SpringBootTest
    public class FlightRepoTest {
        @Autowired
        private FlightDepartureRepo repo;
        
        @Test
        public void testFindAll() {
            System.out.println(repo.findAll());
        }
    }
    
  • 如果这里返回空,说明是JPA或数据库的问题;如果有数据,再排查GraphQL相关配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:35:19