Graphql Java嵌套查询解析器

时间:2019-05-28 14:16:18

标签: java spring-boot graphql

我有使用Java解析器的需求图嵌套查询。

getAccounts(type: "01",transactionMonths: 12){
         accountNumber,
          openDate,
          productType,               
          accountTransactions(annualFee: True){
            amount,
            date
                }
      }

我们如何在graphql中编写查询以及如何为嵌套查询编写Java解析器。 如何获取嵌套查询参数以传递给我的jparepository。 我的帐户类型和交易类型如下

type Account{
    accountNumber: String
    openDate: String
     type: String
     transactionMonths: String
     productType: String
     accountTransactions:[AccountTransaction]
}
type AccountTransaction{
    amount: String
    date:String
    annualFee:Boolean
}

如何使用Java解析器使用嵌套查询来检索帐户中的accountTransactions。

1 个答案:

答案 0 :(得分:0)

您是否打算按照本link中有关BookResolver的说明实施GraphQLResolver?

如果您阅读以上链接,则应该可以编写如下内容:

public class AccountResolver implements GraphQLResolver<Account> {
   public Collection<AccountTransaction> accountTransactions(Account account) {
       // put your business logic here that will call your jparepository
       // for a given account
   }
}

对于Java DTO,您应该具有以下内容:

public class Account {
    private String accountNumber;
    private String openDate;
    private String type;
    private String transactionMonths;
    private String productType;

    // Don't specify a field for your list of transactions here, it should
    // resolved by our AccountResolver

   public Account(String accountNumber, String openDate, String type, String transactionMonths, String productType) {
       this.accountNumber = accountNumber;
       this.openDate = openDate;
       this.type = type;
       this.transactionMonths = transactionMonths;
       this.productType = productType;
   }

   public String getAccountNumber() {
       return accountNumber;
   }

   public String getOpenDate() {
       return openDate;
   }

   public String getType() {
       return type;
   }

   public String getTransactionMonths() {
       return transactionMonths;
   }

   public String getProductType() {
       return productType;
   }

}

让我再解释一下有关解析器的代码:

  • 您为帐户DTO创建一个新的解析器;
  • 它具有一种方法,其签名与Account中的GraphQL字段完全相同,即: accountTransactions ,返回 AccountTransaction的集合

关于 Java DTO

  • 它指定GraphQL类型的所有字段,但您要解析器解析的字段。

SpringBoot GraphQL将自动连接解析器,如果客户要求提供有关帐户及其交易的详细信息,它将被调用。

假设您已经定义了一个名为 accounts 的GraphQL查询,该查询将返回所有帐户,则以下GraphQL查询将是有效的:

{
    accounts {
        accountNumber
        accountTransactions {
            amount
            date
            annualFee
        }
    }
}
相关问题