Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

GraphQL: Understanding Spring Data JPA/Spring Boot — Part 2

DZone 's Guide to

GraphQL: Understanding Spring Data JPA/Spring Boot — Part 2

This article explores the service layer in GraphQL and looks at an example.

· Database Zone ·
Free Resource

In Part 1, we looked at an example with .graphqls file. In this part, let's understand the service layer.

We have EmployeeService.java, which is used in the controller.

In service, we first need to access a resource, which is the employee.graphqls file via the following code:

@Value("classpath:employee.graphqls")
Resource resource;

We have a method annotated with @PostConstruct, which will be called after our service is initialized.

@PostConstruct
private void loadSchema() throws IOException {


    // get the schema
    File schemaFile = resource.getFile();
    // parse schema
    TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(schemaFile);
    RuntimeWiring wiring = buildRuntimeWiring();
    GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring);
    graphQL = GraphQL.newGraphQL(schema).build();
}
private RuntimeWiring buildRuntimeWiring() {
  return RuntimeWiring.newRuntimeWiring()
              .type("Query", typeWiring -> typeWiring
                      .dataFetcher("allEmployee", allEmployeeDataFetcher))
              .build();
}

In this method, we are parsing the .graphqls file in the registry and passing it to the SchemaGenerator with runTimeWiring. See the "allEmployee" in the runtime wiring, which will map the allEmployee query in employee.graphqls with the allEmployeeDataFetcher. We are setting the GraphQL object from this method, which will be used in the controller.

allEmployeeDataFetcher is simply returning a list of all employees by calling repo.findAll().

@Component
public class AllEmployeeDataFetcher implements DataFetcher<List<Employee>>{
@Autowired
EmployeeRepo repo;

@Override
public List<Employee> get(DataFetchingEnvironment environment) {
return repo.findAll();
}
}

It implements the DataFetcher with the TypeObject as ListOfEmployee. DataFetchingEnvironment lets you access the content of the request if any ID parameters are passed in the request to get the employee of the specific ID.

In our controller, we have:

public ResponseEntity<Object> getEmployeeConfigs(@RequestBody String empReqst)
{
 ExecutionResult execute= service.getGraphQL().execute(empReqst);
 return new ResponseEntity<>(execute, HttpStatus.OK);
}

ExecutionResult's object will contain the result of the query passed as empReqst. Only that data will be present, which is requested in empReqst.

You could refer to GitHub for the full code.

Topics:
graphql ,spring ,tutorial ,database ,spring data jpa ,springboot

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}