Spring GraphQL 使用

干亮
2023-12-01

Spring GraphQL

Spring GraphQL从2022年5月开始的1.0版本,不再需要继承Resolver,使用spring的注解即可实现GraphQL

引入POM

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
        </dependency>
    </dependencies>

配置文件

application.yml配置内容:

spring:
  graphql:
    graphiql:
      enabled: true
    schema:
      printer:
        enabled: true
      locations: classpath:graphql/**/

指定graphql文件存放的位置

在resources/schema目录下创建GraphQL Schema文件

type Query {
    greeting: String
    employees: [Employee]
    employee(id: ID!): Employee!
    employeesByOrganization(organizationId: Int!): [Employee]
    employeesByDepartment(departmentId: Int!): [Employee]
 #   getDepartment11(employee: EmployeeParam): Department!
}

type Mutation {
    updateEmployeeName(input: EmployeeUpdate!): Employee
}


type Employee {
    id: ID!
    organizationId: Int!
    department: Department!
    name: String!
    age: Int!
    position: String!
    salary: Int!
}

type Department {
    id: ID!
    departmentName: String!
}

input EmployeeParam {
    id: ID!
}

input EmployeeUpdate {
    id: ID!
    name: String
}

注解接口实现

最新的Spring GraphQL 提供了基于注解的编程模式,响应GraphQL的类使用@Controller进行注解

@QueryMapping实现查询

@Controller
public class GreetingController {

    private static final Logger logger = LoggerFactory.getLogger(GreetingController.class);

    @Autowired
    private EmployeeMapper employeeMapper;

    @QueryMapping
    public String greeting() {
        return "Hello " + "007";
    }

    @QueryMapping
    public List<Employee> employees() {
        return employeeMapper.findAll();
    }

    @QueryMapping
    public Employee employee(@Argument String id) {
        return employeeMapper.selectByPrimaryKey(Long.valueOf(id));
    }
}

使用的是Chrome浏览器的 Altair Graphal Client插件测试graphQL

查询全部数据:


{
  employees {
    id
    organizationId
    department {
      id
      departmentName
    }
    name
    age
    position
    salary
  }
}

按照参数查询:

{
  employee(id: "1") {
    id
    organizationId
    department {
      id
      departmentName
    }
    name
    age
    position
    salary
  }
}

@MutationMapping变更


@Controller
public class EmployeeQuery {

    @SchemaMapping(typeName = "Employee", field = "department")
    public Department getDepartment11(Employee employee) {
        logger.info("================= SchemaMapping ===============");
        return employeeMapper.selectByPrimaryKey(employee.getId()).getDepartment();

        //        Department department = new Department();
        //        department.setId(1L);
        //        department.setDepartmentName("aa");
        //        return department;

    }

    @MutationMapping
    public Employee updateEmployeeName(@Argument("input") Employee employee) {
        logger.info("================= updateEmployeeName ===============");
        logger.info("update input:{}", employee);
        Employee emp = employeeMapper.selectByPrimaryKey(employee.getId());
        if (null == emp) {
            throw new RuntimeException("222");
        }
        employeeMapper.updateByPrimaryKeySelective(employee);
        return emp;
    }
}

GraphQL变更语句

mutation updateEmployeeName($upe:EmployeeUpdate!){
  updateEmployeeName(input:$upe) {
    id
    organizationId
    department {
      id
      departmentName
    }
    name
    age

  }
}


{
    "upe":{
        "id":1,
        "name":"staturday"
    }
}

@SchemaMapping

@SchemaMapping 研究了很长时间,调用上面的getDepartment11方法一直无法调用通过,后来发现此注解不能直接调用,此注解实现特殊查询,在上面的的employees,通过观察后台日志,日志中下列内容,说明调用了@SchemaMapping注解的方法实现子查询
2022-11-04 18:02:23.108  INFO 24688 --- [nio-8080-exec-1] c.h.g.w.controller.EmployeeQuery         : ================= SchemaMapping ===============

 类似资料: