Вступление
GraphQL — это язык запросов для API. Согласно Wikipedia , «GraphQL был разработан внутри Facebook в 2012 году, а затем был опубликован в 2015 году».
В GraphQL есть много преимуществ:
- Спросите, что вам нужно, и получите это точно
- Получите много ресурсов в одном запросе
- Улучшенная производительность
Ключевые понятия
- Схема (запрос и мутация)
- Resolvers
схема
Определяет, какие данные вы можете получить из запроса. Здесь у нас также есть типы и отношения.
запрос
Это похоже на запрос GET в API REST. Мы будем использовать Query для извлечения данных.
Мутации
Они используются для создания, удаления и обновления данных. Аналогично POST, DELETE и PUT в REST.
Вам также может понравиться: GraphQL:
основные функции, архитектура, плюсы и минусы
Предположим, что у нас есть таблица Person в БД Oracle с полями id, name, firstName, lastName и email. Теперь схема выглядит так:
person.graphqls
Джава
xxxxxxxxxx
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
}
Из примера видно, что метод getperson написан на Query. Он выбирает данные на основе идентификатора, тогда как метод setperson записывается в Mutation. Это создает нового человека.
Resolvers
Теперь нам нужно написать QueryResolver и mutationResolver для реализации методов в запросе и мутации схемы.
Добавление зависимости
В этой статье мы используем Spring Boot. Для поддержки GraphQL в Spring Boot нам нужно добавить некоторые зависимости в pox.xml:
XML
xxxxxxxxxx
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>
Также добавьте зависимости оракула:
XML
xxxxxxxxxx
1
<dependency>
2
<groupId>com.oracle</groupId>
3
<artifactId>ojdbc7</artifactId>
4
<version>12.1.0.1</version>
5
</dependency>
Подключиться к удаленной базе данных Oracle
В application.properties добавьте следующее:
Файлы свойств
xxxxxxxxxx
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
Теперь мы подключены к удаленной базе данных Oracle и добавили зависимости GrapQL и Oracle. Теперь мы добавим схему person в файл person.graphqls.
Создайте сущность, которая должна соответствовать таблице в БД и схеме в perso.graphqls .
Импорт javax.persistence. *;
Джава
xxxxxxxxxx
1
import javax.persistence.*;
2
3
4
name=”person”) (
5
public class Person {
6
7
8
name=”id”, nullable = false) (
9
private int id;
10
11
name=”preferred_name”, nullable = false) (
12
private String name;
13
14
name=”first_name”, nullable = false) (
15
private String firstName;
16
17
name=”last_name”, nullable = false) (
18
private String lastName;
19
20
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
}
Создайте репозиторий для вышеуказанного объекта:
Джава
xxxxxxxxxx
1
import com.example.DemoGraphQL.model.Person;
2
import org.springframework.data.repository.CrudRepository;
3
4
public interface PersonRepository extends CrudRepository<Person, Integer> {
5
}
Теперь нам нужно написать резольвер.
QueryResolver
Джава
xxxxxxxxxx
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:
Джава
xxxxxxxxxx
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
}
Стартер приложения:
Джава
xxxxxxxxxx
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
18
public class DemoGraphQlApplication {
19
20
public static void main(String[] args) {
21
SpringApplication.run(DemoGraphQlApplication.class, args);
22
}
23
24
25
public GraphQLErrorHandler errorHandler() {
26
return new GraphQLErrorHandler() {
27
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
53
public Query query(PersonRepository personRepository) {
54
return new Query(programRepository);
55
}
56
57
58
public Mutation mutation(PersonRepository personRepository) {
59
return new Mutation(personRepository);
60
}
61
62
}
Мы сделали с частью кодирования.
меры
- Создайте файл person.graphqls со схемой
- Подключен к удаленной базе данных Oracle из application.properties
- Создайте сущность для таблицы персонажа, соответствующего схеме
- Реализовано хранилище для сущности
- Написан запрос и преобразователь мутаций.
- тестирование
Перейдите по адресу http: // localhost: 8080 / graphiql .
Напишите запрос:
Джава
xxxxxxxxxx
1
{
2
getPerson(id:225) {
3
id,
4
name,
5
firstName,
6
lastName,
7
email
8
}
9
}
Выполнить.
Вы сделали. Спасибо за прочтение!