Query type in GraphQL with Spring GraphQL and Spring Data R2DBC

In the previous tutorial, I introduced you to GraphQL, the problems that GraphQL solved for the limitations of RESTful Web Service. I also gave you a brief guide on implementing GraphQL’s Query type with Spring GraphQL and Spring Data JPA. In this tutorial, we will learn in more detail how to implement this Query type using Spring GraphQL and Spring Data R2DBC.

First, I will create a Spring Boot project with Web, Spring for GraphQL, Spring Data R2DBC, and PostgreSQL Driver as an example:

Result:

As I said in the previous post, to work with GraphQL, we need to define schema .graphqls files. By default, Spring Boot will scan all directories in the project’s classpath src/main/resources to read these schema files.

I will create a folder called “graphql” in the src/main/resources folder and put the GraphQL schema files in this folder.

As an example, I created a new schema.graphqls file to query all students in the database as follows::

To handle the above Query, first, I will define the Repository class for the “student” table:

as follows:

with Student model with the following content:

Next, we will create a new controller and define a method with the same name as the field name of the above Query type, as follows:

As you can see, the students() method has been annotated with the @QueryMapping annotation so that Spring can scan and map this method name with the field of type Query. Very simple, right?

Behind the sense, the @QueryMapping annotation is implemented using a generic annotation @SchemaMapping:

This @SchemaMapping annotation defines a property typeName which allows us to define the type of GraphQL. Here, our type is Query!

Another property of the @SchemaMapping annotation is the field, which allows Spring to map the field of GraphQL with the name of the method that will handle the request:

By default, if we do not declare a value for this field attribute, its value will be the method name!

If we don’t use the @QueryMapping annotation, we can rewrite the code above using the @SchemaMapping annotation as follows:

For testing convenience, we will add the spring.graphql.graphiql.enabled=true property to enable the use of the GraphiQL tool, in the application.properties file:

The database information is also configured in the application.properties file as follows:

My database has the following students:

Now, if you run this application and query using the “students” field above, you will see the following results:

To pass parameters to a Query, we can define an example like this:

In the controller, we will use the @Argument annotation to bind the parameter defined in the Query field with the parameter in the request handle method:

The name attribute of this @Argument annotation allows us to specify which parameters in the method are bound to which parameters in the Query.

Result when we query:

as follows:

Add Comment