Implement GraphQL With Spring Boot by Connecting to Oracle
In this tutorial, see how to implement GraphQL with Spring Boot by connecting to Oracle DB.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
GraphQL is a query language for APIs. According to Wikipedia, "GraphQL was developed internally by Facebook in 2012 before being publicly released in 2015."
There are many benefits with GraphQL:
- Ask for what you need and get it exactly
- Get many resources in a single request
- Improved performance
Key Concepts
- Schema (Query and Mutation)
- Resolvers
Schema
Determines what data you can fetch from querying. Here, we have types and relationships also.
Query
This is similar to a GET request in REST APIs. We will use Query for fetching the data.
Mutations
They are used to create, delete, and update data. Similar to POST, DELETE, and PUT in REST.
You might also like: GraphQL: Core Features, Architecture, Pros, and Cons
Consider that we have a table called Person in the Oracle DB with fields being id, name, firstName, lastName, and email. Now the schema looks like below:
person.graphqls
xxxxxxxxxx
type Person {
id: Int!
name: String!
firstName: String!
lastName: String!
email: String!
}
type Query {
getPerson(id:Int!): Person
}
type Mutation{
setPerson(id:Int!,name: String!firstName: String!lastName: String!,email:String!):Person
}
We can see from the example that the getperson method is written in Query. It fetches data based on the id, whereas the setperson method is written in the Mutation. It creates a new person.
Resolvers
Now we need to write the QueryResolver and mutationResolver to implement the methods in the schema's query and mutation.
Adding Dependency
In this article, we are using Spring Boot. To support GraphQL in Spring Boot, we need to add some dependencies in pox.xml:
xxxxxxxxxx
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>3.10.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>4.3.0</version>
</dependency>
Also, add the oracle dependencies:
xxxxxxxxxx
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1</version>
</dependency>
To Connect to Remote Oracle DB
In application.properties, add the following:
xxxxxxxxxx
spring.datasource.url=jdbc:oracle:thin:@//<IP>:1521/oracl
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
We are now connected to remote Oracle DB and have added GrapQL and Oracle dependencies. Now we will add the person schema to the person.graphqls file.
Create an Entity that should match both the table in the DB and the schema in perso.graphqls.
Import javax.persistence.*;
xxxxxxxxxx
import javax.persistence.*;
name=”person”) (
public class Person {
name=”id”, nullable = false) (
private int id;
name=”preferred_name”, nullable = false) (
private String name;
name=”first_name”, nullable = false) (
private String firstName;
name=”last_name”, nullable = false) (
private String lastName;
name=”email”, nullable = false) (
private String email;
public Person(){
}
public Person(int id, String name, String firstName, String lastName, String email) {
this.id = id;
this.coreID = coreID;
this.name = name;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Create a repository for the above entity:
xxxxxxxxxx
import com.example.DemoGraphQL.model.Person;
import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, Integer> {
}
Now we need to write a resolver.
QueryResolver
xxxxxxxxxx
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import com.example.DemoGraphQL.model.Person;
import com.example.DemoGraphQL.repository.PersonRepository;
public class Query implements GraphQLQueryResolver {
private PersonRepository personRepository;
public Query(PersonRepository personRepository) {
this.personRepository=personRepository;
}
public Person getPerson(int id){
Person person=personRepository.findOne(125);
return person;
}
}
MutationResolver:
xxxxxxxxxx
package com.example.DemoGraphQL.resolver;
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
import com.example.DemoGraphQL.repository.PersonRepository;
public class Mutation implements GraphQLMutationResolver {
PersonRepository personRepository;
public Mutation(PersonRepository personRepository) {
this.personRepository = personRepository;
}
public Person newPerson(int id, String name,String firstName, String lastName, String email) {
Person person = new Person();
person.setId(id);
person.setName(name);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setEmail(email);
personRepository.save(author);
return person;
}
}
Application starter:
xxxxxxxxxx
package com.example.DemoGraphQL;
import com.example.DemoGraphQL.exception.GraphQLErrorAdapter;
import com.example.DemoGraphQL.repository.PersonRepository;
import com.example.DemoGraphQL.resolver.Query;
import com.example.DemoGraphQL.resolver.Mutation;
import graphql.ExceptionWhileDataFetching;
import graphql.GraphQLError;
import graphql.servlet.GraphQLErrorHandler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DemoGraphQlApplication {
public static void main(String[] args) {
SpringApplication.run(DemoGraphQlApplication.class, args);
}
public GraphQLErrorHandler errorHandler() {
return new GraphQLErrorHandler() {
public List<GraphQLError> processErrors(List<GraphQLError> errors) {
List<GraphQLError> clientErrors = errors.stream()
.filter(this::isClientError)
.collect(Collectors.toList());
List<GraphQLError> serverErrors = errors.stream()
.filter(e -> !isClientError(e))
.map(GraphQLErrorAdapter::new)
.collect(Collectors.toList());
List<GraphQLError> e = new ArrayList<>();
e.addAll(clientErrors);
e.addAll(serverErrors);
return e;
}
protected boolean isClientError(GraphQLError error) {
return !(error instanceof ExceptionWhileDataFetching || error instanceof Throwable);
}
};
}
public Query query(PersonRepository personRepository) {
return new Query(programRepository);
}
public Mutation mutation(PersonRepository personRepository) {
return new Mutation(personRepository);
}
}
We are done with the coding part.
Steps
- Create a person.graphqls file with schema
- Connected to remote oracle db from application.properties
- Create a entity for table person matching the schema
- Implemented repository for the Entity
- Written the query and mutation resolver.
- Testing
Navigate to http://localhost:8080/graphiql.
Write the query:
xxxxxxxxxx
{
getPerson(id:225) {
id,
name,
firstName,
lastName,
email
}
}
Execute.
You're done. Thanks for reading!
Further Reading
Published at DZone with permission of sai kumar javvaji. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments