DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis

Trending

  • Alternative Structured Concurrency
  • GenAI Implementation Isn't Magic — It’s a Lifecycle
  • Why Stable RAG Answers Can Still Hide Unstable Evidence
  • Slopsquatting: Building a Scanner That Catches AI-Hallucinated Packages Before They Reach Production
  1. DZone
  2. Data Engineering
  3. Databases
  4. Implement GraphQL With Spring Boot by Connecting to Oracle

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.

By 
sai kumar javvaji user avatar
sai kumar javvaji
·
Jan. 31, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
24.1K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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

Java
xxxxxxxxxx
1
16
 
1
type Person {
2
id: Int!
3
name: String!
4
firstName: String!
5
lastName: String!
6
email: String!
7
}
8
9
type Query {
10
getPerson(id:Int!): Person
11
12
}
13
14
type Mutation{ 
15
setPerson(id:Int!,name: String!firstName: String!lastName: String!,email:String!):Person
16
}

 

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:

XML
xxxxxxxxxx
1
10
 
1
<dependency>
2
<groupId>com.graphql-java</groupId>
3
<artifactId>graphql-spring-boot-starter</artifactId>
4
<version>3.10.0</version>
5
</dependency>
6
<dependency>
7
<groupId>com.graphql-java</groupId>
8
<artifactId>graphql-java-tools</artifactId>
9
<version>4.3.0</version>
10
 </dependency>


Also, add the oracle dependencies:

XML
xxxxxxxxxx
1
 
1
<dependency>
2
<groupId>com.oracle</groupId>
3
<artifactId>ojdbc7</artifactId>
4
<version>12.1.0.1</version>
5
</dependency>


To Connect to Remote Oracle DB

In application.properties, add the following:

Properties files
xxxxxxxxxx
1
 
1
spring.datasource.url=jdbc:oracle:thin:@//<IP>:1521/oracl
2
spring.datasource.username=username
3
spring.datasource.password=password
4
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.*;

Java
xxxxxxxxxx
1
76
 
1
import javax.persistence.*;
2
3
@Entity
4
@Table(name=”person”)
5
public class Person {
6
7
@Id
8
@Column(name=”id”, nullable = false)
9
private int id;
10
11
@Column(name=”preferred_name”, nullable = false)
12
private String name;
13
14
@Column(name=”first_name”, nullable = false)
15
private String firstName;
16
17
@Column(name=”last_name”, nullable = false)
18
private String lastName;
19
20
@Column(name=”email”, nullable = false)
21
private String email;
22
23
public Person(){
24
25
}
26
27
public Person(int id, String name, String firstName, String lastName, String email) {
28
this.id = id;
29
this.coreID = coreID;
30
this.name = name;
31
this.firstName = firstName;
32
this.lastName = lastName;
33
this.email = email;
34
}
35
36
public int getId() {
37
return id;
38
}
39
40
public void setId(int id) {
41
this.id = id;
42
}
43
44
45
public String getName() {
46
return name;
47
}
48
49
public void setName(String name) {
50
this.name = name;
51
}
52
53
public String getFirstName() {
54
return firstName;
55
}
56
57
public void setFirstName(String firstName) {
58
this.firstName = firstName;
59
}
60
61
public String getLastName() {
62
return lastName;
63
}
64
65
public void setLastName(String lastName) {
66
this.lastName = lastName;
67
}
68
69
public String getEmail() {
70
return email;
71
}
72
73
public void setEmail(String email) {
74
this.email = email;
75
}
76
}


Create a repository for the above entity:

Java
xxxxxxxxxx
1
 
1
import com.example.DemoGraphQL.model.Person;
2
import org.springframework.data.repository.CrudRepository;
3
4
public interface PersonRepository extends CrudRepository<Person, Integer> {
5
 }

 

Now we need to write a resolver. 

QueryResolver

Java
xxxxxxxxxx
1
24
 
1
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
2
import com.example.DemoGraphQL.model.Person;
3
import com.example.DemoGraphQL.repository.PersonRepository;
4
5
public class Query implements GraphQLQueryResolver {
6
7
private PersonRepository personRepository;
8
9
10
11
public Query(PersonRepository personRepository) {
12
13
this.personRepository=personRepository;
14
15
}
16
17
18
public Person getPerson(int id){
19
20
Person person=personRepository.findOne(125);
21
return person;
22
23
}
24
}

 

MutationResolver:

Java
xxxxxxxxxx
1
28
 
1
package com.example.DemoGraphQL.resolver;
2
3
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
4
import com.example.DemoGraphQL.repository.PersonRepository;
5
6
public class Mutation implements GraphQLMutationResolver {
7
8
PersonRepository personRepository;
9
public Mutation(PersonRepository personRepository) {
10
this.personRepository = personRepository;
11
12
}
13
14
public Person newPerson(int id, String name,String firstName, String lastName, String email) {
15
Person person = new Person();
16
person.setId(id);
17
person.setName(name);
18
person.setFirstName(firstName);
19
person.setLastName(lastName);
20
person.setEmail(email);
21
22
personRepository.save(author);
23
24
return person;
25
}
26
27
28
}

 

Application starter:

Java
xxxxxxxxxx
1
62
 
1
package com.example.DemoGraphQL;
2
3
import com.example.DemoGraphQL.exception.GraphQLErrorAdapter;
4
import com.example.DemoGraphQL.repository.PersonRepository;
5
import com.example.DemoGraphQL.resolver.Query;
6
import com.example.DemoGraphQL.resolver.Mutation;
7
import graphql.ExceptionWhileDataFetching;
8
import graphql.GraphQLError;
9
import graphql.servlet.GraphQLErrorHandler;
10
import org.springframework.boot.SpringApplication;
11
import org.springframework.boot.autoconfigure.SpringBootApplication;
12
import org.springframework.context.annotation.Bean;
13
import java.util.ArrayList;
14
import java.util.List;
15
import java.util.stream.Collectors;
16
17
@SpringBootApplication
18
public class DemoGraphQlApplication {
19
20
public static void main(String[] args) {
21
SpringApplication.run(DemoGraphQlApplication.class, args);
22
}
23
24
@Bean
25
public GraphQLErrorHandler errorHandler() {
26
return new GraphQLErrorHandler() {
27
@Override
28
public List<GraphQLError> processErrors(List<GraphQLError> errors) {
29
List<GraphQLError> clientErrors = errors.stream()
30
.filter(this::isClientError)
31
.collect(Collectors.toList());
32
33
List<GraphQLError> serverErrors = errors.stream()
34
.filter(e -> !isClientError(e))
35
.map(GraphQLErrorAdapter::new)
36
.collect(Collectors.toList());
37
38
List<GraphQLError> e = new ArrayList<>();
39
e.addAll(clientErrors);
40
e.addAll(serverErrors);
41
return e;
42
}
43
44
protected boolean isClientError(GraphQLError error) {
45
return !(error instanceof ExceptionWhileDataFetching || error instanceof Throwable);
46
}
47
};
48
}
49
50
51
52
@Bean
53
public Query query(PersonRepository personRepository) {
54
return new Query(programRepository);
55
}
56
57
@Bean
58
public Mutation mutation(PersonRepository personRepository) {
59
return new Mutation(personRepository);
60
}
61
62
}

 

We are done with the coding part.

Steps

  1. Create a person.graphqls file with schema
  2. Connected to remote oracle db from application.properties
  3. Create a entity for table person matching the schema
  4. Implemented repository for  the Entity
  5. Written the query and mutation resolver.
  6. Testing 

Navigate to http://localhost:8080/graphiql.

Write the query:

Java
xxxxxxxxxx
1
 
1
{
2
  getPerson(id:225) {
3
    id,
4
      name,
5
    firstName,
6
    lastName,
7
   email
8
  }
9
}

 

Execute.

You're done. Thanks for reading!

Further Reading

Why and When to Use GraphQL

An Overview of GraphQL

Spring Framework GraphQL Database Spring Boot Schema

Published at DZone with permission of sai kumar javvaji. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook