共计 2505 个字符,预计需要花费 7 分钟才能阅读完成。
2021-01-27 GraphQL 入门(一)
GraphQL GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查问的运行时。GraphQL 对你的 API 中的数据提供了一套易于了解的残缺形容,使得客户端可能精确地取得它须要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建弱小的开发工具。
启动后界面如上图所示
1.1 增加依赖 org.springframework.boot spring-boot-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
复制代码
1.2 编写 graphqls 文件 type Query {pets: [Pet] animals: [Animal] }
type Pet {id: Int type: Animal name: String age: Int}
enum Animal {DOG CAT BADGER MAMMOTH OOOOOO} 自己用的 idea 编写 graphqls 文件,能够装置 graphql 插件,
配置文件类型
1.3 编写实体类 package com.example.demo;
public class Pet {private long id;
private String name;
private Animal type;
private int age;
public Pet(long id, String name, Animal type, int age) {
this.id = id;
this.name = name;
this.type = type;
this.age = age;
}
public Pet() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Animal getType() {
return type;
}
public void setType(Animal type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
复制代码
} package com.example.demo;
public enum Animal {/* Animal */ DOG, CAT, BADGER, MAMMOTH, OOOOOO } 1.4 编写查问组件 package com.example.demo;
import com.coxautodev.graphql.tools.GraphQLQueryResolver; import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.List;
@Component public class Query implements GraphQLQueryResolver {public List pets() {List pets = new ArrayList<>();
Pet aPet = new Pet();
aPet.setId(1L);
aPet.setName("Covey's cat");
aPet.setAge(3);
aPet.setType(Animal.CAT);
pets.add(aPet);
return pets;
}
public List<Animal> animals() {
Animal animal = Animal.MAMMOTH;
Animal animal1 = Animal.BADGER;
Animal animal2 = Animal.CAT;
Animal animal3 = Animal.OOOOOO;
Animal animal4 = Animal.DOG;
List<Animal> animalList = new ArrayList<>(4);
animalList.add(animal);
animalList.add(animal1);
animalList.add(animal2);
animalList.add(animal3);
animalList.add(animal4);
return animalList;
}
复制代码
} 本章节介绍完,前面待续 …
参考资料:
github.com/graphql-jav…
www.graphql-java.com/tutorials/g…
graphql.cn/code/#serve…