Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot GraphQL @QueryMapping not being called

I had some trouble setting up graphql in a spring boot project and I wanted to make a checklist for anyone trying to set this up as well. My answer is down below:

like image 803
brando f Avatar asked Aug 13 '26 17:08

brando f


1 Answers

Steps:

Add graphql dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Create .graphqls file:

  • create at least one 'type Query'
  • create at least one 'type "your object name"'
  • it should go under src/main/resources/graphql
type Query {
    myQuery(firstName: String): Obj
}

type Obj {
    name: String
    description: String
}

Create Object

  • create an object with members with names that match the names of the object you defined in the .graphqls file
public class Obj
{
    private String name;
    private String description; 
   
    ...
}

Create Controller

  • create class with @Controller annotation
  • add method in that class with an @QueryMapping annotation
  • If needed add an @Argument annoation to the method paramater
  • Make sure the query name in the .graphqls file matches the method name
  • Make sure method parameter name matches the query param in the .graphqls file


import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;


@Controller
public class AttractionsGraphql {

    private final DAO yourDatabaseAccessObject;

    @QueryMapping
    public Obj myQuery(@Argument String firstName) {
        return yourDatabaseAccessObject.getObj(firstName);
    }
}

Add this to your application.properties file to use the graphql ui to call your endpoint:

spring.graphql.graphiql.enabled=true

Start up your app and you can test your endpoint at http://localhost:8080/graphiql?path=/graphql with the graphql ui.

Hitting [shift + space] in the query window you can see what possible parameters you can get from your schema. Here's an example query:

query whateverName {
  myQuery (firstName: "bob") {
    name
    description
    
  }
}

Hope this helps! These two sites helped me figure this out:

  • https://www.baeldung.com/spring-graphql
  • https://spring.io/guides/gs/graphql-server/

If your object has a nested object you'd need to make a method with an @SchemaMapping in your controller. The links above go into that

like image 165
brando f Avatar answered Aug 15 '26 08:08

brando f



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!