依赖
GraphQL相关依赖如下(SpringBoot2.X):
<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>graphql-java-tools</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
核心代码
建立graphql文件
root.graphqls -- 接口定义
#查询入口
type Query {
####### Author相关 #########
findAuthorById(id:ID!): Author
findAllAuthors: [Author]!
####### Book相关 #########
findAllBooks: [Book]!
findBookById(id:ID!): Book!
}
type Mutation {
newAuthor(firstName: String!,lastName: String!) : Boolean!
saveBook(input: BookIn!) : Boolean!
}
schema.graphqls -- 报文定义
type Author {
#作者Id
id: BigInteger!
#创建时间
createdTime: String
#名
firstName: String
#姓
lastName: String
#该作者的所有书籍
books: [Book]
}
type Book {
id: ID!
title: String!
isbn: String!
pageCount: Int
author: Author
authorBatch: Author
}
input BookIn {
title: String!
isbn: String!
pageCount: Int
authorId: BigInteger!
}
base.graphqls -- 自定义标量(数据类型)
# 自定义标量类型:Long
scalar Long
scalar BigInteger
Query
Query主要实现查询功能:
@Component
public class Query implements GraphQLQueryResolver {
@Resource
private BookService bookService;
@Resource
private AuthorService authorService;
// public List<Author> findAllAuthors() {
// return authorService.list();
// }
//
// public Author findAuthorById(Long id) {
// return authorService.getById(id);
// }
public List<Book> findAllBooks() {
return bookService.list();
}
public Book findBookById(Long id) {
return bookService.getById(id);
}
}
Mutation
Mutation主要实现新增、修改、删除等功能:
@Component
public class Mutation implements GraphQLMutationResolver {
@Resource
private BookService bookService;
@Resource
private AuthorService authorService;
public boolean newAuthor(String firstName, String lastName) {
Author author = new Author();
author.setLastName(lastName);
author.setFirstName(firstName);
return authorService.save(author);
}
public boolean saveBook(Book input) {
return bookService.save(input);
}
}
其他
graphql
还可以结合dataloader
来解决N+1
问题,详细参考源码。
源码
https://gitee.com/lifengdi/graphql-demo
除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接
加油!