Graphql на java со сложными объектами

Я много искал в Google, а также в stackoverflow. Большинство примеров относятся к весеннему ботинку. Я новичок в Springboot. и я очень запутался в том, как получить данные с помощью graphql. В приведенном ниже примере у меня есть одна группа отчетов, в которой может быть несколько отчетов.

How do I fetch details of group along with custom report details?

What should I user? Resolver/DataFetcher?

If resolver please help me with proper explanation

Результат должен быть:

{
    group{
       name : xyz
       reports [
       {
          id:7
          name : report1
       },
       {
         id:8
         name : report2
       },
       {
         id:9
         name : report3
       }
      ]
  }    

}

ReportGroup class

@Entity
@Table(name = "reportgroup")
public class ReportGroup{
  private String name;
  private List<CustomReport> customReports;
}

public String getName() {
    return this.name;
}

public void setName(final String name) {
    this.name = name;
}

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "report_group_custom_report", joinColumns = {
        @JoinColumn(name = "REPORT_GROUP_ID") }, inverseJoinColumns = {
                @JoinColumn(name = "CUSTOM_REPORT_ID") })
public List<CustomReport> getCustomReports() {
    return this.customReports;
}

Rest api call that returns group along with reports

@RequestMapping(value = "/secure/getReportGroupDetail/{name}", method = RequestMethod.POST)
public ResponseBody<GroupDTO> getReportGroupDetail(
    @PathVariable("id") final Integer id,
    final HttpServletRequest request) throws RecordNotFoundException {
final ReportGroup group = this.reportGroupService.getReportGroupDetail(id);     
return new ResponseBody(dto, Constants.SUCCESS);
}

GroupService.java

@Transactional(readOnly = true)
    public ReportGroup getReportGroupDetail(final Integer id){
return this.reportGroupDAO
                .findById(id);

}

Schema:

schema {
    query: Query
}
type Query {
    reportgroup:ReportGroup
}

type ReportGroup{
    name:String!,
     customReport : [CustomReport]
}

DataFetcher

public class ReportGroupDataFetcher implements DataFetcher<ReportGroup> {

@Autowired
ReportGroupService reportGroupService;

@Override
public Group get(final DataFetchingEnvironment env) {   
    Group   group = this.reportGroupService.getReportGroupDetail(1);        
    return group;
}

}

The Controller

@RequestMapping(value = "/secure/getGroupDetail", method = RequestMethod.POST)
    public ResponseBody<Object> getGroupDetail(     
            @RequestBody final JsonData jsonData,
            final HttpServletRequest request)  {
        final JSONObject jsonRequest = new JSONObject(jsonData.getData());  
        final GraphQL graphQL = this.schemaBuilder.getGraphQL();        
        final ExecutionInput executionInput = ExecutionInput.newExecutionInput()
                .query(jsonRequest.getString("query")).build();     
        final ExecutionResult executionResult = graphQL.execute(executionInput);        
        return new ResponseBody(executionResult, Constants.SUCCESS);
    }

To Load Schema

public class SchemaBuilder {
@Autowired
ReportGroupDataFetcher reportgroupDataFetcher;


public GraphQL getGraphQL() {
    final SchemaParser schemaParser = new SchemaParser();
    final SchemaGenerator schemaGenerator = new SchemaGenerator();
    final File schemaFile = new File(myFileName);
    final TypeDefinitionRegistry typeRegistry = schemaParser
            .parse(schemaFile);
    final RuntimeWiring wiring = buildRuntimeWiring();
    final GraphQLSchema graphQLSchema = schemaGenerator
            .makeExecutableSchema(typeRegistry, wiring);
    return GraphQL.newGraphQL(graphQLSchema).build();
}

private RuntimeWiring buildRuntimeWiring() {
    return RuntimeWiring.newRuntimeWiring().type("Query",
            typeWiring -> typeWiring                        
                    .dataFetcher("reportgroup", this.reportgroupDataFetcher))               
            .build();
    }


 }
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
0
0
1 168
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вам также необходимо определить данные вашей группы клиентов. Попробуйте что-нибудь подобное ниже.

  schema {
        query: Query
    }
    type CustomReport{
    id:Int!,
    name:String!

    }
    type Query {
        reportgroup:ReportGroup
    }

    type ReportGroup{
        name:String!,
         customReport : [CustomReport]
    }

Другие вопросы по теме