
本文档旨在指导开发者如何在spring boot graphql客户端中处理对象列表。我们将探讨如何构建graphql查询以传递对象列表,并提供使用graphqltemplate的示例代码,展示如何配置请求并解析响应,以便在客户端应用中有效地获取和使用graphql服务返回的数据。
在构建GraphQL客户端时,一个常见的需求是向服务器传递对象列表作为查询参数。本文将介绍如何在spring boot应用中使用 GraphQLTemplate 处理这种情况。我们将重点关注如何构建GraphQL查询、传递参数以及解析响应。
构建GraphQL查询
首先,我们需要定义GraphQL查询。假设服务端有一个查询 getPersonsByIds,它接收一个 personIds 列表作为参数,并返回一个 Person 对象的列表。查询语句如下:
query($personIds: [BigInteger]) { getPersonsByIds(personIds : $personIds ) { firstName middleName lastName birthDt } }
在这个查询中,$personIds 是一个变量,类型为 [BigInteger],表示一个 BigInteger 类型的列表。服务端需要定义对应的schema,例如:
type Person{ firstName: String // other fields... } type Query { personList: [Person] }
并且使用 @SchemaMapping 注解来返回对象列表:
@SchemaMapping(typeName = "Query",value = "personList") public List<Person> getPersonsByIds() { return personService.getPersonsByIds(); }
使用GraphQLTemplate发送请求
接下来,我们将使用 GraphQLTemplate 发送GraphQL请求。以下代码展示了如何构建 GraphQLRequestEntity 并传递 personIds 列表:
@Service public class PersonService { private final GraphQLTemplate graphQLTemplate = new GraphQLTemplate(); private final String url = "http://localhost:8084/graphql"; public List<Person> getPersonsByIds(List<BigInteger> personIds) { GraphQLRequestEntity requestEntity; try { requestEntity = GraphQLRequestEntity.Builder() .url(url) .requestMethod(GraphQLTemplate.GraphQLMethod.QUERY) .request("query($personIds: [BigInteger]) {n" + " getPersonsByIds(personIds : $personIds ) {n" + " firstNamen" + " middleNamen" + " lastNamen" + " birthDtn" + " }n" + "}" ) .variables(new Variable<>("personIds", personIds)) // 传递personIds列表 .build(); } catch (MalformedURLException e) { throw new RuntimeException(e); } return graphQLTemplate.query(requestEntity, ResponseGetPersonsByIds.class).getResponse().getGetPersonsByIds(); } }
关键在于 variables 方法的调用。我们将变量名 “personIds” 和实际的 personIds 列表传递给 Variable 构造函数。
定义响应类
为了能够解析GraphQL响应,我们需要定义一个响应类 ResponseGetPersonsByIds。这个类应该包含一个 getPersonsByIds 字段,类型为 List<Person>。
public class ResponseGetPersonsByIds { private GetPersonsByIdsResponse response; public GetPersonsByIdsResponse getResponse() { return response; } public void setResponse(GetPersonsByIdsResponse response) { this.response = response; } public static class GetPersonsByIdsResponse { private List<Person> getPersonsByIds; public List<Person> getGetPersonsByIds() { return getPersonsByIds; } public void setGetPersonsByIds(List<Person> getPersonsByIds) { this.getPersonsByIds = getPersonsByIds; } } }
注意事项
- 确保服务端GraphQL schema正确定义了接收列表参数的查询。
- GraphQLTemplate 库的版本可能会影响API的使用方式,请参考库的官方文档。
- 错误处理:在实际应用中,应该添加适当的错误处理机制,例如处理 MalformedURLException 和GraphQL查询失败的情况。
- 类型匹配:确保客户端传递的参数类型与服务端GraphQL schema定义的类型匹配,避免类型转换错误。
总结
通过本文,我们学习了如何在Spring Boot GraphQL客户端中使用 GraphQLTemplate 传递对象列表作为查询参数。关键步骤包括构建GraphQL查询、使用 variables 方法传递参数以及定义响应类。遵循这些步骤,可以轻松地构建GraphQL客户端,并与提供GraphQL API的服务端进行交互。


