问题描述
我在使用 graphql
中的输入数据
进行搜索时遇到问题:
I have problem searching with using Input data
in graphql
:
@RestController
@RequestMapping("/api/dictionary/")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DictionaryController {
@Value("classpath:items.graphqls")
private Resource schemaResource;
private GraphQL graphQL;
private final DictionaryService dictionaryService;
@PostConstruct
public void loadSchema() throws IOException {
File schemaFile = schemaResource.getFile();
TypeDefinitionRegistry registry = new SchemaParser().parse(schemaFile);
RuntimeWiring wiring = buildWiring();
GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, wiring);
graphQL = GraphQL.newGraphQL(schema).build();
}
private RuntimeWiring buildWiring() {
DataFetcher<String> fetcher9 = dataFetchingEnvironment ->
getByInput((dataFetchingEnvironment.getArgument("example")));
return RuntimeWiring.newRuntimeWiring()
.type("Query", typeWriting ->
typeWriting
.dataFetcher("getByInput", fetcher9)
)
.build();
}
public String getByInput(Character character) {
return "testCharacter";
}
}
items.graphqls
文件内容:
type Query {
getByInput(example: Character): String
}
input Character {
name: String
}
在请求这样的资源时:
query {
getByInput (example: {name: "aa"} )
}
字符DTO:
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Character {
protected String name;
}
我有一个错误:
"Exception while fetching data (/getByInput) : java.util.LinkedHashMap cannot be cast to pl.graphql.Character",
查询应如何显示?
修改
如果我更改为:
public String getByInput(Object character)
代码运行正常-但我想转换为工作.
The codes runs fine - but i want convert to work.
推荐答案
对于类型为 input
类型的输入参数, graphql-java
会将其转换为地图
.
For the input argument which the type is the input
type , graphql-java
will convert it to a Map
.
在您的情况下,查询为 getByInput(示例:{name:"aa"})
,其中 example
参数是 input
类型.所以,
In your case the query is getByInput (example: {name: "aa"} )
which the example
argument is the input
type . So ,
dataFetchingEnvironment.get("example");
将返回一个结构为(key ="name",value ="aa")的Map.然后,您尝试将地图转换为 Character
,这肯定会给您一个错误,因为它们完全是不同种类.
will return a Map with the structure (key="name" , value="aa") .Then you try to cast the map to Character
which definitely gives you an error since they are totally different types.
要将Map转换为 Character
, graphql-java
不会帮助您进行此类转换.您必须自己实施转换代码,或使用其他库,例如 Jackson和Gson,推土机或任何您喜欢的库,用于将地图转换为您的域对象(即角色).
To convert a Map to a Character
, graphql-java
will not help you for such conversion. You have to implement the conversion codes by yourselves or use other libraries such as Jackson , Gson , Dozer or whatever libraries you like for converting a map to your domain object (i.e. Character).
这篇关于Graphql使用输入类型来搜索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!