graphql java如何使用
GraphQL Java 使用指南
依赖配置
在 Maven 或 Gradle 项目中添加 GraphQL Java 依赖。Maven 配置示例:
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>20.4</version>
</dependency>
定义 Schema
使用 GraphQL Schema Definition Language (SDL) 或编程方式定义 Schema。SDL 示例:
type Query {
bookById(id: ID): Book
}
type Book {
id: ID
name: String
pageCount: Int
}
编程方式构建 Schema 示例:
GraphQLObjectType bookType = newObject()
.name("Book")
.field(newFieldDefinition().name("id").type(GraphQLID))
.field(newFieldDefinition().name("name").type(GraphQLString))
.field(newFieldDefinition().name("pageCount").type(GraphQLInt))
.build();
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(newObject()
.name("Query")
.field(newFieldDefinition()
.name("bookById")
.type(bookType)
.argument(newArgument("id", GraphQLID))
.dataFetcher(environment -> {
String id = environment.getArgument("id");
return fetchBookById(id); // 自定义数据获取逻辑
}))
.build()
.build();
执行查询
通过 GraphQL 对象执行查询:
GraphQL graphQL = GraphQL.newGraphQL(schema).build();
ExecutionInput input = ExecutionInput.newExecutionInput()
.query("{ bookById(id: \"book-1\") { id name pageCount } }")
.build();
ExecutionResult result = graphQL.execute(input);
String jsonResult = new ObjectMapper().writeValueAsString(result.toSpecification());
数据加载优化
使用 DataLoader 批量处理 N+1 查询问题:
DataLoader<String, Book> bookLoader = DataLoader.newDataLoader(keys ->
CompletableFuture.supplyAsync(() -> batchLoadBooks(keys)));
ExecutionInput input = ExecutionInput.newExecutionInput()
.query("{ bookById(id: \"book-1\") { id name } }")
.dataLoaderRegistry(registry -> registry.register("book", bookLoader))
.build();
错误处理
自定义错误处理策略:
GraphQL graphQL = GraphQL.newGraphQL(schema)
.defaultDataFetcherExceptionHandler(new SimpleDataFetcherExceptionHandler() {
@Override
public List<GraphQLError> handleException(DataFetcherExceptionHandlerParameters handlerParameters) {
Throwable exception = handlerParameters.getException();
if (exception instanceof BookNotFoundException) {
return Collections.singletonList(new CustomGraphQLError("Book not found"));
}
return super.handleException(handlerParameters);
}
})
.build();
订阅支持
实现实时数据订阅:
GraphQLObjectType subscriptionType = newObject()
.name("Subscription")
.field(newFieldDefinition()
.name("bookUpdates")
.type(bookType)
.dataFetcher(environment -> {
Publisher<Book> publisher = createBookPublisher();
return publisher;
}))
.build();
GraphQLSchema schema = GraphQLSchema.newSchema()
.subscription(subscriptionType)
.build();
工具集成
结合 Spring Boot 使用 graphql-java-kickstart 工具:
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>12.0.0</version>
</dependency>
在 Spring 中通过注解方式定义解析器:

@GraphQLQuery
public Book bookById(@GraphQLArgument(name = "id") String id) {
return bookService.findById(id);
}






