• 使用Spring Boot和JPA创建GraphQL API


    GraphQL既是API查询语言,也是使用当前数据执行这些查询的运行时。GraphQL让客户能够准确地要求他们所需要的东西,仅此而已,使API随着时间的推移更容易发展,并通过提供API中数据的清晰易懂的描述,支持强大的开发工具。

    在本文中,我们将创建一个简单的机场位置应用程序。

    生成项目

    去 https://start.spring.io/ 并生成一个项目,不要忘记添加Spring Web、H2数据库和Spring DATA JPA依赖项。

    添加依赖项

    要启用GraphQL的使用,请在下面添加这两个依赖项。

    <dependency>
      <groupId>com.<a href="https://javakk.com/tag/graphql" title="查看更多关于 graphql 的文章" target="_blank">graphql</a>-java</groupId>
      <artifactId><a href="https://javakk.com/tag/graphql" title="查看更多关于 graphql 的文章" target="_blank">graphql</a>-spring-boot-starter</artifactId>
      <version>5.0.2</version>
    </dependency>
    
    <dependency>
      <groupId>com.<a href="https://javakk.com/tag/graphql" title="查看更多关于 graphql 的文章" target="_blank">graphql</a>-java</groupId>
      <artifactId><a href="https://javakk.com/tag/graphql" title="查看更多关于 graphql 的文章" target="_blank">graphql</a>-java-tools</artifactId>
      <version>5.2.4</version>
    </dependency>

    Schema

    GraphQL模式定义了通过API可用的数据点。模式描述了数据类型及其关系,以及可用的操作,例如检索数据的查询和创建、更新和删除数据的突变。

    在resources文件夹中,创建一个扩展名为“.graphqls”的文件,全名为“ location.graphqls ”。

    //Define the Entity attribute
    type Location {
     id: ID!
     name: String!
     address: String!
    }
    
    type Query {
     findAllLocations: [Location]!
    }
    
    type Mutation {
     newLocation(name: String!, address: String) : Location!
     deleteLocation(id:ID!) : Boolean
     updateLocationName(newName: String!, id:ID!) : Location!
    }

    “ ! ”表示该字段为必填字段。

    Entity 和 Repository

    现在创建一个名为 Location 的实体。该位置应该有三个属性: id 、 name 和 address ,如模式中所述。当然,也会产生 Getters, Setters, 和 Constrictors。

    然后,在本例中,存储库只使用CrudRepository,并扩展位置实体。

    //imports...
    
    public interface LocationRepository extends CrudRepository<Location, Long> {
    }

    Queries & Exceptions

    1. 查询:

    查询允许我们检索数据。每个查询可以有一个特定的对象,它完全基于查询中指定的字段返回,您可以添加或删除字段以匹配您需要的确切数据,以适合您的特定用例。

    创建一个解析器包,然后添加一个实现 GraphQLQueryResolver 的新查询类,并添加 @Component 注释。我们只需要添加之前在location中输入的 location.graphqls 。

    //imports...
    
    @Component
    public class Query implements GraphQLQueryResolver {
        private LocationRepository locationRepository;
    
        public Query(LocationRepository locationRepository) {
            this.locationRepository = locationRepository;
        }
    
        public Iterable<Location> findAllLocations() {
            return locationRepository.findAll();
        }
    }

    2. Mutator:

    GraphQL中的Mutator允许它更新存储在服务器上的数据。与查询不同,创建、更新或删除等Mutator会改变数据。

    现在创建一个mutator包,然后添加一个实现 GraphQLMutationResolver 和添加 @Component 注释的新类 Mutation 。另外,添加我们之前输入的 location.graphqls 。

    //imports...
    
    @Component
    public class Mutation implements GraphQLMutationResolver {
        private LocationRepository locationRepository;
    
        public Mutation(LocationRepository locationRepository) {
            this.locationRepository = locationRepository;
        }
    
        public Location newLocation(String name, String address) {
            Location location = new Location(name, address);
            locationRepository.save(location);
            return location;
        }
    
        public boolean deleteLocation(Long id) {
            locationRepository.deleteById(id);
            return true;
        }
    
        public Location updateLocationName(String newName, Long id) {
            Optional<Location> optionalLocation =
                    locationRepository.findById(id);
    
            if(optionalLocation.isPresent()) {
                Location location = optionalLocation.get();
                location.setName(newName);
                locationRepository.save(location);
                return location;
            } else {
                throw new LocationNotFoundException("Location Not Found", id);
            }
        }

    3. Exceptions:

    创建一个异常包,然后添加一个新的类 LocationNotFoundException ,该类扩展 RuntimeException 并实现 GraphQLError 。

    //imports...
    
    public class LocationNotFoundException extends RuntimeException implements GraphQLError {
    
        private Map<String, Object> extensions = new HashMap<>();
    
        public LocationNotFoundException(String message, Long invalidLocationId) {
            super(message);
            extensions.put("invalidLocationId", invalidLocationId);
        }
    
        @Override
        public List<SourceLocation> getLocations() {
            return null;
        }
    
        @Override
        public Map<String, Object> getExtensions() {
            return extensions;
        }
    
        @Override
        public ErrorType getErrorType() {
            return ErrorType.DataFetchingException;
        }

    现在GraphQL API已经可以使用了!

  • 相关阅读:
    非插件方式为wordpress添加一个额外的编辑器
    Linux常用命令
    You辉编程_kafka
    华为数据中心机房集成解决方案
    node.js 用 xml2js.Parser 读 Freeplane.mm文件,生成测试用例.csv文件
    服务器数据恢复- Ext4文件系统分区挂载报错的数据恢复案例
    2022-09-07 mysql/stonedb-查询优化器逻辑记录及优化器魔改
    Dockerfile 命令详解及最佳实践
    webservice原始调用(无论是java的webservice还是.net或是php的都可用)
    解决Docker启动之npm版本不兼容问题
  • 原文地址:https://blog.csdn.net/JavaShark/article/details/125523451