首页 > Java > java教程 > 正文

GraphQL Spring Boot 客户端:处理对象列表的查询

DDD
发布: 2025-10-31 15:44:01
原创
368人浏览过

graphql spring boot 客户端:处理对象列表的查询

本文档旨在指导开发者如何使用 Spring Boot 构建 GraphQL 客户端,并重点解决如何向 GraphQL 服务传递对象列表进行查询的问题。我们将通过示例代码演示如何配置 GraphQLTemplate,并展示如何构建包含对象列表的请求,最后给出最佳实践建议,帮助读者高效地进行 GraphQL 客户端开发。

在使用 Spring Boot 构建 GraphQL 客户端时,一个常见的需求是向 GraphQL 服务传递对象列表作为查询参数。本文将介绍如何使用 GraphQLTemplate 来实现这一目标,并提供详细的代码示例和注意事项。

使用 GraphQLTemplate 发送包含对象列表的查询

GraphQLTemplate 是一个方便的工具,可以简化与 GraphQL 服务的交互。以下是如何使用它来发送包含对象列表的查询:

  1. 依赖引入:

首先,确保你的项目中引入了 com.github.americanexpress:nodes 依赖。在 pom.xml 文件中添加以下内容:

<dependency>
    <groupId>com.github.americanexpress</groupId>
    <artifactId>nodes</artifactId>
    <version>0.5.0</version>
</dependency>
登录后复制
  1. 构建 GraphQL 请求:

构建 GraphQLRequestEntity 时,需要正确设置变量,将对象列表作为参数传递。以下是一个示例:

import com.americanexpress.nodes.graphql.GraphQLRequestEntity;
import com.americanexpress.nodes.graphql.GraphQLTemplate;
import com.americanexpress.nodes.graphql.Variable;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;
import java.math.BigInteger;

@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" +
                    "    firstName\n" +
                    "    middleName\n" +
                    "    lastName\n" +
                    "    birthDt\n" +
                    "  }\n" +
                    "}"
                )
                .variables(new Variable<>("personIds", personIds))
                .build();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        return graphQLTemplate.query(requestEntity, ResponseGetPersonsByIds.class).getResponse().getGetPersonsByIds();
    }

    public static void main(String[] args) {
        PersonService personService = new PersonService();
        // 示例:传递一个包含两个 ID 的列表
        List<BigInteger> ids = Arrays.asList(new BigInteger("2477142261427744786"), new BigInteger("2477142261427744787"));
        List<Person> persons = personService.getPersonsByIds(ids);
        System.out.println(persons);
    }
}
登录后复制

代码解释:

表单大师AI
表单大师AI

一款基于自然语言处理技术的智能在线表单创建工具,可以帮助用户快速、高效地生成各类专业表单。

表单大师AI74
查看详情 表单大师AI
  • GraphQLRequestEntity.Builder(): 用于构建 GraphQL 请求实体。
  • .url(url): 设置 GraphQL 服务的 URL。
  • .requestMethod(GraphQLTemplate.GraphQLMethod.QUERY): 指定请求方法为 QUERY。
  • .request(...): 定义 GraphQL 查询语句。注意查询语句中使用了变量 $personIds,类型为 [BigInteger],表示一个 BigInteger 类型的列表。
  • .variables(new Variable<>("personIds", personIds)): 将变量 personIds 绑定到实际的 personIds 列表。 Variable 构造函数的第一个参数是变量名(必须与查询语句中的变量名一致),第二个参数是变量的值。
  • graphQLTemplate.query(requestEntity, ResponseGetPersonsByIds.class): 执行查询,并将结果映射到 ResponseGetPersonsByIds 类。
  1. 定义GraphQL Schema (服务端):

服务端需要定义相应的 GraphQL Schema,包括 Person 类型和 getPersonsByIds 查询。例如:

type Person {
    firstName: String
    middleName: String
    lastName: String
    birthDt: String
}

type Query {
    getPersonsByIds(personIds: [BigInteger]): [Person]
}
登录后复制
  1. 服务端实现 (Spring GraphQL):

使用 @SchemaMapping 将 getPersonsByIds 查询映射到 Java 方法。

import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

import java.math.BigInteger;
import java.util.List;

@Controller
public class PersonController {

    private final PersonService personService;

    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @QueryMapping
    public List<Person> getPersonsByIds(@Argument List<BigInteger> personIds) {
        return personService.getPersonsByIdsFromDatabase(personIds); // 假设 personService 有一个从数据库获取数据的方法
    }
}
登录后复制

注意事项:

  • 确保服务端 GraphQL Schema 中 getPersonsByIds 的参数类型与客户端传递的类型一致(例如,[BigInteger])。
  • ResponseGetPersonsByIds 类需要根据实际的 GraphQL 响应结构进行定义,用于正确地映射查询结果。
  • 错误处理:在实际应用中,需要添加适当的错误处理机制,例如处理 MalformedURLException 和 GraphQL 服务返回的错误。

总结

通过使用 GraphQLTemplate 和正确构建 GraphQLRequestEntity,可以方便地向 Spring Boot GraphQL 客户端传递对象列表。 关键在于正确定义 GraphQL 查询语句中的变量类型,并在 variables 中将变量名与实际的对象列表绑定。 同时,需要确保服务端 Schema 定义与客户端请求参数类型一致。

以上就是GraphQL Spring Boot 客户端:处理对象列表的查询的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号