In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about the integration of Graphql Query in SpringBoot development. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Overview
As a very popular software architecture style for modern network applications, REST is loved by the majority of WEB developers. REST can be seen everywhere in the current software architecture design pattern, but with the popularity and development of REST, one of its biggest shortcomings begins to be exposed:
In many cases, the data needed by the client is often similar in different places, but it is not the same.
For example, for the same user information, in some scenarios, the front end only needs the user's brief information (name, avatar), while in other scenarios, the user's details are needed. When there are many similar but different places, it is necessary to develop more interfaces to meet the needs of the front end.
As there are more and more such scenarios, there are more and more interfaces, documents become more and more bloated, and the cost of front-end communication increases exponentially.
Based on the above scenario, we urgently need a solution or framework so that the required interface fields can be specified by the front end when using the data interface of the same domain model (DO, DTO), while the back end automatically adapts and returns the corresponding fields according to the needs of the front end.
This is our protagonist GraphQL today.
Scene simulation
Consider the following scenario:
There is an one-to-many relationship between users and articles. One user can publish multiple articles, and at the same time, they can find the corresponding authors according to the articles.
We need to build the following Graphql queries:
Get the details of the user according to the user ID and get all the articles published by this user
Get the details of the article and the information of the author according to the article ID
Of course, the project is based on SpringBoot development.
Development practice
Before formal development, I recommend that you install the JS GraphQL plug-in on IDEA. This plug-in is convenient for us to write Schema, syntax error correction, code highlighting and so on.
Create a SpringBoot project
Create a SpringBoot project through IDEA and introduce the corresponding jar
Org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-web com.graphql-java graphql-spring-boot-starter 5.0.2 com.graphql-java graphql-java-tools 5.2.4 org.projectlombok lombok
Here we mainly need to introduce graphql-spring-boot-starter and graphql-java-tools.
Create a Java entity class
User
@ Data public class User {private int userId; private String userName; private String realName; private String email; private List posts; public User () {} public User (int userId, String userName, String realName, String email) {this.userId = userId; this.userName = realName; this.email = email;}}
Post
@ Data public class Post {private int postId; private String title; private String text; private String category; private User user; public Post () {} public Post (int postId, String title, String text, String category) {this.postId = postId; this.title = text; this.category = category;}}
Two JAVA entities are defined: Post,User.
Write Schema files
Create a GraphQL Schema file in the resources/schema directory
Schema {query: Query,} type Query {# get specific user getUserById (id:Int): User # get specific blog getPostById (id:Int): Post} type User {userId: ID, userName: String, realName: String, email: String, posts: [Post],} type Post {postId: ID, title: string, text: String Category: String user: User,}
As above, we define two objects, User and Post, through the type keyword. Add after the attribute! Indicates that this is a non-empty attribute, and indicates that it is a Post collection by [Post], similar to List in the Java object.
Two query objects, getUserById,getPostById, are defined by the Query keyword, which returns the User object and the Post object respectively.
For the syntax of schema, please refer to the link: https://graphql.org/learn/schema
Write business logic
PostService
@ Service public class PostService implements GraphQLQueryResolver {/ * for testing, only query the result with an id of 1 * / public Post getPostById (int id) {if (id = = 1) {User user = new User (1, "javadaily", "Graphql Daily Log", "zhangsan@qq.com"); Post post = new Post (1, "Hello,Graphql", "first experience of Java", "Diary") Post.setUser (user); return post;} else {return null;} UserService@Service public class UserService implements GraphQLQueryResolver {List userList = Lists.newArrayList (); public User getUserById (int id) {return userList.stream (). Filter (item-> item.getUserId () = = id). FindAny (). OrElse (null) } @ PostConstruct public void initUsers () {Post post1 = new Post (1, "Hello,Graphql1", "Graphql first experience 1", "Diary"); Post post2 = new Post (2, "Hello,Graphql2", "Graphql first experience 2", "Diary"); Post post3 = new Post (3, "Hello,Graphql3", "Graphql first experience 3", "Diary"); List posts = Lists.newArrayList (post1,post2,post3) User user1 = new User (1, "zhangsan", "Zhang San", "zhangsan@qq.com"); User user2 = new User (2, "lisi", "Li Si", "lisi@qq.com"); user1.setPosts (posts); user2.setPosts (posts); userList.add (user1); userList.add (user2);}}
The query based on Graphql needs to implement the GraphQLQueryResolver interface, because we have not introduced the data layer for demonstration, please know.
Configure Graphql Endpoint server.port = 8080 graphql.servlet.corsEnabled=true # configure Endpoint graphql.servlet.mapping=/graphql graphql.servlet.enabled=true
After configuring the ports and endpoints, we can test the Graphql interface we wrote.
The interface address is: localhost:8080/graphql
test
Here I use the Altair Graphal Client plug-in for Chrome browser, and of course you can also use other client-side tools, such as graphql-playground.
Install the plug-in
The browser enters chrome://extensions/, to add to the browser after searching for Altair in the extension center.
Query
Start the SpringBoot project, and then in the open Altair plug-in interface, enter the Graphql endpoint http://localhost:8080/graphql, then click Docs, move the mouse over the desired query, and click ADD QUERY to add the corresponding query.
Click Send Request to see the query result:
Then we can add or delete the interface field and request the interface again in Query according to our needs. We will see that the response result will also be returned automatically according to our request:
Summary
The data operations supported by Graphql are:
Query (Query): a basic query that gets data.
Mutation: supports operations such as adding, deleting and modifying data.
Subscription (Subscription): used to listen for changes in data and push changing messages to the other party based on protocols such as websocket.
After reading the above, do you have any further understanding of how to integrate Graphql Query in SpringBoot development? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.