Mutation type in GraphQL with Spring GraphQL and Spring Data R2DBC

In the previous tutorial, I showed you how to type Query in GraphQL and also used Spring GraphQL together with Spring Data R2DBC to implement GraphQL request to query student information. To add, edit, or delete student information with GraphQL, we need to use type Mutation. How to implement type Mutation with Spring GraphQL? Let’s find out together with me in this tutorial!

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

Result:

I will define the Repository class for the “student” table:

as follows:

with Student model with the following content:

As an example, I created a new schema.graphqls file that defines the Mutation type to add new student information in the database as follows:

According to the GraphQL specification, a Query type is required to be defined in each GraphQL Schema. Here, I simply define a field to get the information of all students.

With the Mutation type, you can only use scalar types such as Int, Float, String, Boolean, and ID in the input parameters of the fields. To use informative inputs, you need to define the input type as I did above with the StudentInput input. The remaining information such as return type, “!” to specify required information, is the same as the definition of Query type!

To implement the Mutation type we defined above with Spring GraphQL, you can add a new Controller with the following content:

Similar to the QueryMapping type using the @QueryMapping annotation, you can use the @MutationMapping annotation to implement the Mutation type. This annotation is also built from the @SchemaMapping annotation with the typeName of “Mutation”, guys:

By default, Spring also scans and maps the method name in the controller with the field of Mutation type to process requests from users.

We will use the annotation @Argument to bind the parameters defined in the field of the Mutation with the parameter in the handle request controller method as you can see.

Now, if you run the application and then try to add a new student:

You will see the following result:

Get the id value of the newly added student then call the request to update the information for this student:

you will see the following result:

Now, if you delete this student information:

you will see the following result:

Add Comment