📅  最后修改于: 2023-12-03 15:31:03.833000             🧑  作者: Mango
GraphQL Java is a library for building GraphQL APIs in Java. With GraphQL Java, developers can define their schema using Java classes, and then use those classes to generate a GraphQL schema.
To use GraphQL Java in your project, you can add the following dependency to your build.gradle
file:
dependencies {
implementation 'com.graphql-java:graphql-java:16.2.0'
implementation 'com.graphql-java:graphql-java-tools:5.2.4'
}
To define a GraphQL schema in Java, you need to create a Java class that represents your GraphQL type. For example, if you want to define a Person
type, you can create a Person
class like this:
public class Person {
private int id;
private String name;
private List<Address> addresses;
public Person(int id, String name, List<Address> addresses) {
this.id = id;
this.name = name;
this.addresses = addresses;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public List<Address> getAddresses() {
return addresses;
}
}
The Person
class has three fields: id
, name
, and addresses
. Each field has a getter method to access the value.
To define a GraphQL schema, you need to use the GraphQLSchema
class. Here's an example of how you can define a schema for the Person
type:
GraphQLObjectType personType = GraphQLObjectType.newObject()
.name("Person")
.field(field -> field.name("id").type(Scalars.GraphQLInt))
.field(field -> field.name("name").type(Scalars.GraphQLString))
.field(field -> field.name("addresses").type(GraphQLList.list(newObject(Address))))
.build();
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(GraphQLObjectType.newObject()
.name("Query")
.field(field -> field
.name("person")
.type(personType)
.argument(arg -> arg.name("id").type(Scalars.GraphQLInt))
.dataFetcher(dataFetchingEnvironment -> {
int id = dataFetchingEnvironment.getArgument("id");
return new Person(id, "John Doe", new ArrayList<>());
})))
.build();
This schema defines a root query field called person
, which takes an id
argument and returns a Person
object. The Person
object has an id
, name
, and addresses
field.
To print a GraphQL schema in Java, you can use the SchemaPrinter
class. Here's an example of how you can print the Person
schema we defined earlier:
String schemaString = new SchemaPrinter().print(schema);
System.out.println(schemaString);
This will print the following schema:
type Person {
id: Int
name: String
addresses: [Address]
}
type Query {
person(id: Int): Person
}
In conclusion, GraphQL Java is a powerful library that allows you to define and generate a GraphQL schema in Java. With the SchemaPrinter
class, you can easily print out your GraphQL schema in a readable format.