DEV Community

lou
lou

Posted on

2

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs