Java use GRAPHQL to build query services detailed _java

Source: Internet
Author: User
Tags int size

Background

With react open source, Facebook has opened up a number of related projects, which have been used within them for many years, which has attracted my attention is that this discussion is GRAPHQL, the official only Nodejs version, because many companies behind the background technology stack is Java, So there is a graphql of the Java version to achieve, in the GitHub can be found, nonsense not to say, directly to see the code, the specific introduction or to the reader Internet cafes, or on the topic.

Graphqlschema

Schema is equivalent to a database, it has a lot of graphqlfielddefinition composition, field is equivalent to database tables/views, each table/view by name, query parameters, data structure, data composition.

1 first define a data structure (graphqloutputtype) field, and then define an initialization method

Private Graphqloutputtype usertype;

private void Initoutputtype () {
   /**
    * Member Object Structure */
   usertype = NewObject ()
       . Name ("User").
       Field ( Newfielddefinition (). Name ("id"). Type (Graphqlint). Build ())
       . Field (Newfielddefinition (). Name (' age '). Type ( Graphqlint). Build ())
       . Field (Newfielddefinition (). Name (' Sex '). Type (Graphqlint). Build ())
       . Field ( Newfielddefinition (). Name ("name"). Type (graphqlstring). Build ().
       field (Newfielddefinition (). Name ("Pic"). Type (graphqlstring). Build ())
       . Build ();


2 define two tables/views, which include name, query parameters, data structure, and the database retrieval device.

 /** * Query Individual user information * @return * * Private graphqlfielddefinition Createuserfield () {return graphqlfielddefinit
        Ion.newfielddefinition (). Name ("user"). argument (Newargument (). Name ("id"). Type (Graphqlint). Build ()) . Type (usertype). Datafetcher (Environment-> {//get query parameter int id = environment.getargument (

          "id");
          Execute the query and use some test data to illustrate the problem. User user = new user ();
          User.setid (ID);
          User.setage (ID + 15);
          User.setsex (id% 2);
          User.setname ("name_" + ID);
          User.setpic ("PIC_" + ID + ". jpg");
        return user;
  }). build (); /** * Query multiple member information * @return * * Private graphqlfielddefinition Createusersfield () {return graphqlfielddef 
        Inition.newfielddefinition (). Name ("users"). argument (Newargument (). Name ("page"). Type (Graphqlint). Build ()) . argument (Newargument (). Name ("size"). Type (Graphqlint). Build ()). ArgumENT (Newargument (). Name ("name"). Type (graphqlstring). Build ()). Type (new Graphqllist (usertype)). Datafetcher (
          Environment-> {//Get query parameter int page = environment.getargument ("page");
          int size = environment.getargument ("size");

          String name = environment.getargument ("name");
          Execute the query, here casually use some test data to illustrate the problem list<user> List = new arraylist<> (size);
            for (int i = 0; i < size; i++) {User user = new user ();
            User.setid (i);
            User.setage (i + 15);
            User.setsex (i% 2);
            User.setname (name + "_" + page + "_" + i);
            User.setpic ("pic_" + i + ". jpg");
          List.add (user);
        } return list;
  }). build ();

 }

3 then define a schema and initialize it, which contains a name and one or more tables/views (Field)

 Private Graphqlschema schema;

  Public Graphschema () {
    initoutputtype ();
    schema = Graphqlschema.newschema (). Query (NewObject ()
        . Name ("Graphquery")
        . Field (Createusersfield ())
        . Field (Createuserfield ()). Build ()
        ). Build ();
  

4 after the completion of the above steps, you also need to define a model, the class name is not limited to, but the structure needs to meet the previous definition of the data structure, and must be public

public class User {
  private int id;
  private int age;
  private int sex;
  private String name;
  Private String pic;
  Getter, setter ...
}  

5) Then write a main method to test the

public static void Main (string[] args) {
    Graphqlschema schema = new Graphschema (). GetSchema ();

    String Query1 = "{Users (page:2,size:5,name:\" john\ ") {id,sex,name,pic}}";
    String Query2 = "{User (Id:6) {id,sex,name,pic}}";
    String Query3 = "{User (Id:6) {id,sex,name,pic},users (page:2,size:5,name:\" john\ ") {id,sex,name,pic}}";

    map<string, object> result1 = (map<string, object>) New GRAPHQL (Schema). Execute (query1). GetData ();
    map<string, object> result2 = (map<string, object>) New GRAPHQL (Schema). Execute (QUERY2). GetData ();
    map<string, object> result3 = (map<string, object>) New GRAPHQL (Schema). Execute (query3). GetData ();

    Query user list
    System.out.println (RESULT1);
    Query individual user
    System.out.println (result2);
    Single user, check with user list
    System.out.println (RESULT3);



Output:

{users=[{id=0, sex=0, Name=john_2_0, pic=pic_0.jpg}, {id=1, sex=1, Name=john_2_1, pic=pic_1.jpg}, {id=2, sex=0, name= John_2_2, pic=pic_2.jpg}, {id=3, sex=1, Name=john_2_3, pic=pic_3.jpg}, {id=4, sex=0, Name=john_2_4, pic=pic_4.jpg}]}
{user={id=6, sex=0, Name=name_6, pic=pic_6.jpg}}
{user={id=6, sex=0, Name=name_6, pic=pic_6.jpg}, Users=[{id=0, sex=0, Name=john_2_0, pic=pic_0.jpg}, {id=1, sex=1, name= John_2_1, pic=pic_1.jpg}, {id=2, sex=0, Name=john_2_2, pic=pic_2.jpg}, {id=3, sex=1, Name=john_2_3, pic=pic_3.jpg}, {id= 4, Sex=0, Name=john_2_4, pic=pic_4.jpg}]}

6 finally put the main method inside the code into the Web layer, only need to define a query parameters, it is easy to set up the query service, Datafetcher inside or call the original query interface

7) Introduction of Maven dependency

<dependency>
  <groupId>com.graphql-java</groupId>
  <artifactid>graphql-java</ artifactid>
  <version>2.0.0</version>
</dependency>

about what the GRAPHQL query definition, look at this may be helpful to you

Json


{
  id=6, 
  sex=0, 
  name= "Name_6", 
  pic= "Pic_6.jpg"
}

Query

{
  id,
  sex,
  name,
  pic
}

The latter part, in fact, is the JSON string that removes the result of = and value, or is readable

Conclusion

Graphql brought a whole new way of thinking, it simplifies the development of Web APIs by specifying what data is required by the client, what data is returned from the server, reducing unnecessary traffic, being friendly to the mobile side, and providing a variety of data aggregation queries, and multiple queries using only one request to meet API minimum granularity, Also meet front-end needs, reduce requests, improve performance.

It feels like it will develop in this direction.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.