[

](xrio.medium.com/?source=pos…)
5月27日
-
3分钟阅读
[
拯救
Spring GraphQL入门
Spring与GraphQL的结合

这篇文章是在Spring应用中使用GraphQL的第一步。
但首先,让我们了解一下GraphQL的情况。根据Red Hat的说法,GraphQL是一种查询语言和应用程序接口(API)的服务器端运行时间,它的重点是只为客户提供他们需要的信息。
创建GraphQL的目的是为了使API快速、通用、对开发者友好。它甚至可以在GraphiQL集成开发环境(IDE)中使用。GraphQL是REST的替代方案,允许开发者创建查询,在一次API调用中从各种来源拉取数据。
此外,GraphQL允许API管理员添加或删除字段而不影响现有的查询。开发人员可以使用他们选择的任何技术来创建API,而GraphQL定义将确保他们为客户提供一致的工作。
项目的想法
我们要建立的项目是一个简单的学校/学生查找所有的端点--只是这次使用GraphQL,它允许我们改变和突变我们的响应数据结构。
学生将有一个ID、名字、电子邮件和学校,每个学校有一个ID和一个名字。
学生实体
@Entity@Data@NoArgsConstructorpublic class Student { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String name; private String email; // Lazy fetch to avoid having the infinite loop @ManyToOne(fetch = FetchType.LAZY) private School school; public Student(String name, String email, School school) { this.name = name; this.email = email; this.school = school; }}
学生资源库
@Repositorypublic interface StudentRepository extends JpaRepository<Student, Long> {}
学校实体
@Entity@Data@NoArgsConstructorpublic class School { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String name; @OneToMany private List<Student> students; public School(String name) { this.name = name; }}
学校资源库
@Repositorypublic interface SchoolRepository extends JpaRepository<School, Long> {}
现在我们用一个简单的findAll 端点为学生和学校创建了控制器,首先是学生的。
@Controller@AllArgsConstructorpublic class StudentController {
学校的控制器将与学生的类似。
@Controller@AllArgsConstructorpublic class SchoolController { SchoolRepository schoolRepository; @QueryMapping List<School> schools(){ return schoolRepository.findAll(); }}
在我们的主类中,我们持久化了一组演示数据,接下来我们会看到。
当然,我们还需要设置我们的GraphQL模式,在resources 文件夹内,我们创建了另一个名为graphql 的文件,其中包含一个名为schema.graphqls(resources>graphql>schema.graphqls)的文件。
该模式应该是这样的。
type Query { students:[Student] schools:[School]}type Student { id: ID! name: String! email: String! school: School!}type School{ id: ID! name: String!}
最后是结果!你可以在http://localhost:8080/graphiql,使用GraphiQL接口。
让我们试着检索一下只显示他们名字的学生列表。

现在,让我们按ID、名字和电子邮件来获取他们。

让我们把他们的学校添加到结果中。

同时,我们可以检索学校。

当然,我们也可以用同一个查询来检索Students 和学校。

最后
由于GraphQL的结果操作,它对任何项目都有很大的好处;这只是在Spring保护伞下使用GraphQL的第一步而已
请在我的GitHub存储库中找到源代码。