2年前 (2022-04-25)  相关技术 |   抢沙发  317 
文章评分 0 次,平均分 0.0

使用Spring Boot和JPA创建GraphQL API

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

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

使用Spring Boot和JPA创建GraphQL API

生成项目

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

使用Spring Boot和JPA创建GraphQL API

添加依赖项

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

<dependency>
  <groupId>com.graphql-java</groupId>
  <artifactId>graphql-spring-boot-starter</artifactId>
  <version>5.0.2</version>
</dependency>

<dependency>
  <groupId>com.graphql-java</groupId>
  <artifactId>graphql-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

使用Spring Boot和JPA创建GraphQL API

现在创建一个名为Location的实体。该位置应该有三个属性:idnameaddress,如模式中所述。当然,也会产生 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已经可以使用了!

参考:

https://www.graphql-java.com

https://graphql.org

 

除特别注明外,本站所有文章均为老K的Java博客原创,转载请注明出处来自https://javakk.com/2620.html

关于

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册