DEV Community

lou
lou

Posted on

GraphQL in Java EE Application

In a Maven-based development, start by adding the GraphQl dependency to your pom.xml file

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-graphql</artifactId> </dependency> 
Enter fullscreen mode Exit fullscreen mode

Create a directory in your resources and create a file with the name schema.graphqls

This file is gonna contain a schema that defines each field of your object and it's type.

To define the schema we'll use a special graphql dsl referred to as SDL.

SDL example:

type Query { gundamWings: [Gundam] } type Gundam { name: String type: String pilot: Pilot } type Pilot { id: String name: String Affiliation: String } type Mutation{ addGundam(gundam:Gundam):Gundam } 
Enter fullscreen mode Exit fullscreen mode

The last step is to add a Controller

@Controller public class GundamWingsGraphQlController { @Autowired private GundamWingsRepository gundamWingsRepository; @QueryMapping public List<Gundam> gundamWingsList(){ return gundamWingsRepository.findAll(); } @MutationMapping public Gundam addGundam(@Argument Gundam gundam){ return gundamWingsRepository.save(gundam); } } 
Enter fullscreen mode Exit fullscreen mode

The first method is for listing the data and the second one is to add an object.

Top comments (0)