graphql - Graphql - 查询返回 null
问题描述
我正在使用用于 java 的graphql-java-annotations库从我的 spring 后端检索数据。
<dependency>
<groupId>io.github.graphql-java</groupId>
<artifactId>graphql-java-annotations</artifactId>
<version>7.1</version>
</dependency>
当我调用查询时,它总是返回 null。
这是我的提供者类:
GraphQLAnnotations graphqlAnnotations = new GraphQLAnnotations();
GraphQLSchema graphQLSchema = newSchema()
.query(graphqlAnnotations.object(QueryTest.class))
.build();
this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
这是查询:
@GraphQLName("queryTest")
public class QueryTest {
@GraphQLField
public static Test byId(final DataFetchingEnvironment env, @GraphQLName("id") Long id) {
return new Test();
}
}
最后是 Test.class
@GraphQLName("Test")
public class Test {
private String id;
private String name;
public Test() {
this("0");
}
public Test(String id) {
this.setName("Name" + id);
this.setId(id);
}
@GraphQLField
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@GraphQLField
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
这是我的电话:
{
"query" : "query queryTest { byId(id: 2) { getId } }",
"operationName" : "queryTest"
}
这是我得到的结果:
{
"data": {
"byId": null
}
}
我调试了graphql执行,发现架构包含TestClass和Test。所以类型和查询是已知的。使用此配置,我没有提取器或解析器。
解决方案
找到了解决方案:
为了通过 AnnotationsSchemaCreator Builder 正确创建架构,我必须更改我的 Provider 类:
GraphQLSchema graphQLSchema = AnnotationsSchemaCreator.newAnnotationsSchema()
.query(QueryTest.class)
.typeFunction(new ZonedDateTimeFunction())
.build();
this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();