GraphQL-Java v8.0+Spring Boot v1.5.10 Fragment未定义错误排查
Let's break down why you're hitting this UndefinedFragment error and how to fix it quickly:
The Root Cause
First off, I notice you've included the UserFields fragment directly in your GraphQL schema definition—and that's the problem! Fragments are part of your query request, not your schema. The schema is meant to define the types and operations available in your API, while fragments are reusable pieces of query logic that live alongside the actual queries you execute.
Step 1: Clean Up Your Schema
Remove the fragment definition from your schema entirely. Your corrected schema should look like this:
type School { id: ID name: String address: String age: String jobTitle: String } type Query { user (id: String!): School! } schema { query: Query }
Step 2: Include the Fragment in Your Query Request
You need to include the UserFields fragment within the same query document as your main query. Here's the correct query format that will resolve the error:
# Define the fragment first fragment UserFields on School { age jobTitle } # Then your main query that uses the fragment { user (id: "123") { ...UserFields } }
Additional Checks for Spring Boot + GraphQL-Java
If you're constructing queries programmatically in your Spring Boot app (instead of receiving them from a client), make sure you're parsing the entire query document (including the fragment) with GraphQL-Java's DocumentParser. For example:
String queryDocument = """ fragment UserFields on School { age jobTitle } { user (id: "123") { ...UserFields } } """; GraphQLSchema schema = // Your pre-built schema instance GraphQL graphQL = GraphQL.newGraphQL(schema).build(); ExecutionResult result = graphQL.execute(queryDocument);
If you're accepting queries from a frontend client, double-check that the client sends the full query document containing both the fragment definition and the main query—missing either will trigger the same error.
Why This Works
GraphQL needs to resolve the fragment's definition at execution time. By moving the fragment into the query document (where it belongs), the parser can locate and apply it to your user query, eliminating the UndefinedFragment error entirely.
内容的提问来源于stack exchange,提问作者Simple-Solution

