Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Spring Boot and JPA to create GraphQL API

Shulou Source: shulou.com Published: 2022-05-31 19:11:23 09月21日 Update

This article focuses on "how to use Spring Boot and JPA to create GraphQL API", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Spring Boot and JPA to create GraphQL API.

First, generate the project

Go to https://start.spring.io/ and build a project, and don't forget to add Spring Web, H2 database, and Spring DATA JPA dependencies.

1. Add dependencies

To enable the use of GraphQL, add these two dependencies below.

Com.graphql-java graphql-spring-boot-starter 5.0.2 com.graphql-java graphql-java-tools 5.2.4 II, Schema

The GraphQL schema defines the data points available through API. The schema describes the data types and their relationships, as well as the available operations, such as queries to retrieve data and mutations to create, update, and delete data.

In the resources folder, create a file with the extension ".graphqls" and the full name "location.graphqls".

/ / Define the Entity attributetype 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: stringency, id:ID!): Location!}

"!" Indicates that the field is required.

III. Entity and Repository

Now create an entity called Location. The location should have three properties: id, name, and address, as described in the schema. Of course, there will also be Getters, Setters, and Constrictors.

Then, in this case, the repository uses only CrudRepository and extends the location entity.

/ / imports...public interface LocationRepository extends CrudRepository {} IV, Queries & Exceptions1. Query

Queries allow us to retrieve data. Each query can have a specific object that is returned entirely based on the fields specified in the query, and you can add or remove fields to match the exact data you need to suit your specific use case.

Create a parser package, then add a new query class that implements GraphQLQueryResolver, and add the @ Component annotation. We just need to add the location.graphqls that we entered in location earlier.

/ / imports...@Componentpublic class Query implements GraphQLQueryResolver {private LocationRepository locationRepository; public Query (LocationRepository locationRepository) {this.locationRepository = locationRepository;} public Iterable findAllLocations () {return locationRepository.findAll ();} 2. Mutator

Mutator in GraphQL allows it to update data stored on the server. Unlike queries, Mutator such as creating, updating, or deleting changes the data.

Now create a mutator package, and then add a new class Mutation that implements GraphQLMutationResolver and adds the @ Component annotation. In addition, add the location.graphqls we entered earlier.

/ / imports...@Componentpublic class Mutation implements GraphQLMutationResolver {private LocationRepository locationRepository; public Mutation (LocationRepository locationRepository) {this.locationRepository = locationRepository;} public Location newLocation (String name, String address) {Location location = newLocation (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 optionalLocation = locationRepository.findById (id); if (optionalLocation.isPresent ()) {Location location = optionalLocation.get (); location.setName (newName); locationRepository.save (location); return location;} else {throw new LocationNotFoundException ("LocationNotFound", id) }} 3. Exceptions

Create an exception package, and then add a new class LocationNotFoundException that extends RuntimeException and implements GraphQLError.

/ / imports...public class LocationNotFoundException extends RuntimeException implements GraphQLError {private Map extensions = new HashMap (); public LocationNotFoundException (String message, Long invalidLocationId) {super (message); extensions.put ("invalidLocationId", invalidLocationId);} @ Override public List getLocations () {return null;} @ Override public Map getExtensions () {return extensions;} @ Override public ErrorType getErrorType () {return ErrorType.DataFetchingException } at this point, I believe you have a deeper understanding of "how to create GraphQL API using Spring Boot and JPA". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Data query field schema update location content entity file comment project storage learning retrieval generation input different practical deeper three Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Apple Shulou Technology macOS MariaDB