实体类看这里:https://blog.csdn.net/qq_26896085/article/details/104854058
创建一个employee.graphqls文件
#这里的Date为处定义的标量,在文件的开始进行声明
scalar Date
schema {
query: EmployeeQuery
}
type EmployeeQuery {
employee(empNo:Int) : Employee
}
type Employee {
empNo: Int
birthDate: Date
firstName: String
lastName: String
hireDate: Date
gender: String
}
DateScalarType.java
写法参考源码Scalars中的写法
package com.woodie.modifyoriginal;
import graphql.schema.*;
import java.text.SimpleDateFormat;
import java.util.Date;
// 需要继承GraphQLScalarType
public class DateScalarType extends GraphQLScalarType {
public DateScalarType() {
super("Date", "Date value", new Coercing<String, String>() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public String serialize(Object input) {
return sdf.format(input);
}
public String parseValue(Object input) {
return this.serialize(sdf.format(input));
}
public String parseLiteral(Object input) {
if (!(input instanceof Date)) {
throw new CoercingParseLiteralException("Expected AST type 'Date' but was ");
} else {
return sdf.format(input);
}
}
});
}
}
GraphqlSDLDemo.java
package com.woodie;
import com.woodie.entity.Employee;
import com.woodie.modifyoriginal.DateScalarType;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GraphqlSDLDemo {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
String fileName = "employee.graphqls";
String fileContent = IOUtils.toString(GraphqlSDLDemo.class.getClassLoader().getResource(fileName), "utf-8");
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(fileContent);
// 解决的是数据的查询
RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring()
.type("EmployeeQuery", builder ->
builder.dataFetcher("employee", environment ->{
Integer id = environment.getArgument("empNo");
return Employee.builder().birthDate(new Date()).empNo(10001).gender("M").firstName("Woodie").lastName("Wang").hireDate(sdf.parse("2222- 03-14")).build();
})
)
// 有处定义的标量时需要传入自定义的ScallarType()类,
.scalar(new DateScalarType())
.build();
GraphQLSchema graphQLSchema= new SchemaGenerator().makeExecutableSchema(typeRegistry,wiring);
GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();
String query = "{employee(empNo:10001){empNo, birthDate, hireDate, lastName}}";
ExecutionResult result = graphQL.execute(query);
System.out.println(result.toSpecification());
} catch (IOException e) {
e.printStackTrace();
}
}
}