### Using Spring Data Projections with QueryByExampleDataFetcher Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Shows how to use Spring Data projections with Query by Example repositories. Create a projection interface or DTO class and configure it via the `projectAs` method to obtain a `DataFetcher` producing the target type. Includes examples for single and multi-result queries. ```java class Account { String name, identifier, description; Person owner; } interface AccountProjection { String getName(); String getIdentifier(); } // For single result queries DataFetcher dataFetcher = QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).single(); // For multi-result queries DataFetcher> dataFetcher = QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).many(); ``` -------------------------------- ### ExecutionGraphQlServiceTester setup Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Creates an ExecutionGraphQlServiceTester to test directly against an ExecutionGraphQlService without a client. The builder allows customizing ExecutionInput details. ```java // include-code::ServiceSetup[tag=serviceSetup,indent=0] ``` ```java // include-code::ServiceSetup[tag=customServiceSetup,indent=0] ``` -------------------------------- ### WebGraphQlTester setup Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Creates a WebGraphQlTester to process requests through the WebGraphQlInterceptor chain before handing off to ExecutionGraphQlService. The builder allows defining HTTP request details. ```java // include-code::WebSetup[tag=webSetup,indent=0] ``` ```java // include-code::WebSetup[tag=customWebSetup,indent=0] ``` -------------------------------- ### Register reflection hints for manual data fetchers Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/graalvm-native.adoc This snippet is a placeholder for the GraphQlConfiguration example. It shows a RuntimeWiringConfigurer that manually adds a DataFetcher, and uses @RegisterReflectionForBinding to register reflection hints for the Book type and its fields. ```java include-code::GraphQlConfiguration[] ``` -------------------------------- ### Register reflection hints for client types Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/graalvm-native.adoc This snippet is a placeholder for the ProjectService example. It uses @RegisterReflectionForBinding to register reflection hints for the Project type and its fields, which is necessary for client support in a native image. ```java include-code::ProjectService[] ``` -------------------------------- ### Sort argument example Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows how to use a Sort method argument when a SortStrategy bean is present. The example declares an Optional parameter and uses orElse with Sort.by(..). ```java @Controller public class BookController { @QueryMapping public Window books(Optional optionalSort) { Sort sort = optionalSort.orElse(Sort.by(..)); } } ``` -------------------------------- ### QueryByExampleExecutor Repository Interface Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Declare a repository that extends QueryByExampleExecutor to enable Query by Example support. This is the required repository interface for using QueryByExampleDataFetcher. ```java public interface AccountRepository extends Repository, QueryByExampleExecutor { } ``` -------------------------------- ### Subrange argument example Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows how to use a Subrange

method argument for pagination when a CursorStrategy bean is present. The example uses ScrollSubrange to get ScrollPosition and count, with defaults of offset and 20. ```java @Controller public class BookController { @QueryMapping public Window books(ScrollSubrange subrange) { ScrollPosition position = subrange.position().orElse(ScrollPosition.offset()); int count = subrange.count().orElse(20); // ... } } ``` -------------------------------- ### JSON response for namespaced album query Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Example response data for the album query, showing the nested structure with music and album. ```json { "data": { "music": { "album": { "id": "42", "title": "Spring for GraphQL" } } } } ``` -------------------------------- ### Enable HTTP GET support for GraphQlHttpHandler Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/transports.adoc Enable HTTP GET support for GraphQL over HTTP by configuring both the handler and the request predicate. GET is disabled by default and must be enabled explicitly on both components. On GET requests, query and operationName are read as query string parameters, while variables and extensions must be JSON strings. ```java GraphQlHttpHandler httpHandler = GraphQlHttpHandler.builder(webGraphQlHandler) .httpMethods(HttpMethod.GET, HttpMethod.POST) .build(); RequestPredicate predicate = GraphQlRequestPredicates.graphQlHttp("/graphql", Set.of(HttpMethod.GET, HttpMethod.POST)); ``` -------------------------------- ### DGS Codegen example schema Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc A sample GraphQL schema used with DGS Codegen to generate client API classes. Defines a Query with a books field returning a list of Book objects. ```graphql type Query { books: [Book] } type Book { id: ID name: String } ``` -------------------------------- ### Enable HTTP GET on GraphQlSseHandler Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/transports.adoc Enables HTTP GET on GraphQlSseHandler and its RequestPredicate. Useful for browser EventSource clients, which can only issue GET requests. By default, only POST is accepted. ```java GraphQlSseHandler sseHandler = GraphQlSseHandler.builder(webGraphQlHandler) .httpMethods(HttpMethod.GET, HttpMethod.POST) .build(); RequestPredicate ssePredicate = GraphQlRequestPredicates.graphQlSse("/graphql", Set.of(HttpMethod.GET, HttpMethod.POST)); ``` -------------------------------- ### Source method argument example Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows how to access the source (parent) object in a @SchemaMapping method by declaring a parameter of the expected type. The simple name of the Java class can match the GraphQL type, avoiding explicit type name in the annotation. ```java @Controller public class BookController { @SchemaMapping public Author author(Book book) { // ... } } ``` -------------------------------- ### Customize GraphQlSource.Builder with GraphQlSourceBuilderCustomizer Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Declare a GraphQlSourceBuilderCustomizer bean to customize the GraphQlSource.Builder, for example to set a custom ExecutionIdProvider. The bean is detected by the Boot Starter and applied during builder initialization. ```java @Configuration(proxyBeanMethods = false) public class GraphQlConfig { @Bean public GraphQlSourceBuilderCustomizer sourceBuilderCustomizer() { return (builder) -> builder.configureGraphQl((graphQlBuilder) -> graphQlBuilder.executionIdProvider(new CustomExecutionIdProvider())); } } ``` -------------------------------- ### @ProjectedPayload interface example Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows how to use @ProjectedPayload interfaces to access GraphQL arguments in controller methods, with @Argument for individual arguments and without for top-level arguments. Includes a SpEL expression in @Value to combine fields. ```java @Controller public class BookController { @QueryMapping public Book bookById(BookIdProjection bookId) { // ... } @MutationMapping public Book addBook(@Argument BookInputProjection bookInput) { // ... } } @ProjectedPayload interface BookIdProjection { Long getId(); } @ProjectedPayload interface BookInputProjection { String getName(); @Value("#{target.author + ' ' + target.name}") String getAuthorAndName(); } ``` -------------------------------- ### Retrieve subscription stream Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Starts a subscription stream using retrieveSubscription, similar to retrieve but returning a stream of responses decoded to data. The Flux may terminate with SubscriptionErrorException or GraphQlTransportException; cancel the Flux to end the subscription. ```java include-code::RetrieveSubscription[tag=subscriptionRetrieve,indent=0] ``` -------------------------------- ### DataLoader.load and dispatchAndJoin Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Demonstrates how to load individual and multiple keys using a DataLoader and then dispatch to fetch the actual data. ```APIDOC ## DataLoader.load and dispatchAndJoin ### Description Loads one or more keys into a DataLoader and then dispatches the loading to retrieve the actual data, blocking until results are available. ### Method load, loadMany, dispatchAndJoin ### Parameters - **key** (K) - Required - The key to load. - **keys** (List) - Required - A list of keys to load. ### Request Example ```java DataLoader loader = dataLoaderRegistry.getDataLoader(Book.class.getName()); loader.load(1L); loader.loadMany(Arrays.asList(2L, 3L)); List books = loader.dispatchAndJoin(); // actual loading ``` ### Response - **books** (List) - The loaded books. ### Response Example ```java assertThat(books).hasSize(3); assertThat(books.get(0).getName()).isEqualTo("..."); ``` ``` -------------------------------- ### Query, Mutation, and Subscription mapping shortcuts Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows the shortcut annotations @QueryMapping, @MutationMapping, and @SubscriptionMapping, which preset the typeName to Query, Mutation, and Subscription respectively. ```java @Controller public class BookController { @QueryMapping public Book bookById(@Argument Long id) { // ... } @MutationMapping public Book addBook(@Argument BookInput bookInput) { // ... } @SubscriptionMapping public Flux newPublications() { // ... } } ``` -------------------------------- ### Create DataFetchers with QuerydslDataFetcher Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Shows how to build DataFetchers for single, multi, and paginated queries using QuerydslDataFetcher.builder(). ```java // For single result queries DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).single(); // For multi-result queries DataFetcher> dataFetcher = QuerydslDataFetcher.builder(repository).many(); // For paginated queries DataFetcher> dataFetcher = QuerydslDataFetcher.builder(repository).scrollable(); ``` -------------------------------- ### Testing Batch Loading with BatchLoaderRegistry and DataLoader Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc First register batch loaders on a DataLoaderRegistry, then access and test individual DataLoaders by dispatching and joining loads. The first block sets up the registry; the second shows how to load keys and assert results. ```java BatchLoaderRegistry batchLoaderRegistry = new DefaultBatchLoaderRegistry(); // perform registrations... DataLoaderRegistry dataLoaderRegistry = DataLoaderRegistry.newRegistry().build(); batchLoaderRegistry.registerDataLoaders(dataLoaderRegistry, graphQLContext); ``` ```java DataLoader loader = dataLoaderRegistry.getDataLoader(Book.class.getName()); loader.load(1L); loader.loadMany(Arrays.asList(2L, 3L)); List books = loader.dispatchAndJoin(); // actual loading assertThat(books).hasSize(3); assertThat(books.get(0).getName()).isEqualTo("..."); // ... ``` -------------------------------- ### GraphiQL initialization script Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql/src/main/resources/graphiql/index.html JavaScript to initialize GraphiQL with a fetcher that uses the 'path' and 'wsPath' query parameters (defaulting to '/graphql'), enforces same-origin for both HTTP and WebSocket endpoints, and adds the history and explorer plugins. It also reads the XSRF-TOKEN cookie to set the initial headers. ```javascript import React from 'react'; import ReactDOM from 'react-dom/client'; import { GraphiQL, HISTORY_PLUGIN } from 'graphiql'; import { createGraphiQLFetcher } from '@graphiql/toolkit'; import { explorerPlugin } from '@graphiql/plugin-explorer'; import 'graphiql/setup-workers/esm.sh'; const params = new URLSearchParams(window.location.search); const path = params.get("path") || "/graphql"; const url = new URL(path, `${location.protocol}//${location.host}`); if (url.origin !== location.origin) { throw new Error('GraphQL endpoint must resolve to the same origin as this page'); } const wsPath = params.get("wsPath") || "/graphql"; const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsOrigin = `${wsProtocol}//${location.host}`; const subscriptionUrl = new URL(wsPath, wsOrigin); if (subscriptionUrl.origin !== wsOrigin) { throw new Error('GraphQL WebSocket endpoint must resolve to the same origin as this page'); } const gqlFetcher = createGraphiQLFetcher({'url': url, 'subscriptionUrl': subscriptionUrl}); const plugins = [HISTORY_PLUGIN, explorerPlugin()]; const xsrfToken = document.cookie.match(new RegExp('(?:^| )XSRF-TOKEN=([^;]+)')); const initialHeaders = xsrfToken ? `{ "X-XSRF-TOKEN" : "${ xsrfToken[1] }" }` : `{}`; function App() { return React.createElement(GraphiQL, { fetcher: gqlFetcher, defaultEditorToolsVisibility: true, headerEditorEnabled: true, shouldPersistHeaders: true, initialHeaders: initialHeaders, plugins: plugins, }); } const container = document.getElementById('graphiql'); const root = ReactDOM.createRoot(container); root.render(React.createElement(App)); ``` -------------------------------- ### Configure ConnectionTypeDefinitionConfigurer Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Configures the ConnectionTypeDefinitionConfigurer to generate connection types. The Boot Starter registers this configurer by default. ```java GraphQlSource.schemaResourceBuilder() .schemaResources(..) .typeDefinitionConfigurer(new ConnectionTypeDefinitionConfigurer) ``` -------------------------------- ### Extend federated types in subgraph schema Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/federation.adoc Example subgraph schema that extends a federated type Book with a @key and @external field, and defines a local Author type. ```graphql type Book @key(fields: "id") @extends { id: ID! @external author: Author } type Author { id: ID firstName: String lastName: String } ``` -------------------------------- ### Implement WebSocketGraphQlClientInterceptor for connection_init and connection_ack Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Create a WebSocketGraphQlClientInterceptor to handle connection-oriented WebSocket messages. Override connectionInitPayload() to provide the 'connection_init' payload and handleConnectionAck() to process the 'connection_ack' payload. Register it like any other GraphQlClientInterceptor, but note only one such interceptor is allowed. ```java static class MyInterceptor implements WebSocketGraphQlClientInterceptor { @Override public Mono connectionInitPayload() { // ... the "connection_init" payload to send } @Override public Mono handleConnectionAck(Map ackPayload) { // ... the "connection_ack" payload received } } ``` -------------------------------- ### Controller with @BatchMapping for Activity interface Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Java controller using @QueryMapping and @BatchMapping to map the coordinator field for all Activity subtypes. ```java @Controller public class BookController { @QueryMapping public List activities() { // ... } @BatchMapping Map coordinator(List activities) { // Called for all Activity subtypes } } ``` -------------------------------- ### Execute request by document name Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Refers to the document in the file named 'project' and sets the 'slug' variable. ```java // include-code::TesterRequests[tag=documentName,indent=0] ``` -------------------------------- ### Register a mapped batch loader with BatchLoaderRegistry Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Register a mapped batch loader for Author entities by author ID in a configuration class. Inject the BatchLoaderRegistry bean provided by the Boot Starter and call forTypePair with the key and target types, then registerMappedBatchLoader with a function returning Mono>. The DataLoader name defaults to the target entity class name, and can be customized via the builder. ```java @Configuration public class MyConfig { public MyConfig(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Mono }); // more registrations ... } } ``` -------------------------------- ### Configure ConnectionFieldTypeVisitor with Window and Slice adapters Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Creates a CursorStrategy with a ScrollPositionCursorStrategy and Base64 encoder, then builds a ConnectionFieldTypeVisitor that adapts Window and Slice returned from DataFetchers. Register the visitor via GraphQlSource.schemaResourceBuilder().typeVisitors(). ```java CursorStrategy strategy = CursorStrategy.withEncoder( new ScrollPositionCursorStrategy(), CursorEncoder.base64()); // <1> GraphQLTypeVisitor visitor = ConnectionFieldTypeVisitor.create(List.of( new WindowConnectionAdapter(strategy), new SliceConnectionAdapter(strategy))); // <2> GraphQlSource.schemaResourceBuilder() .schemaResources(..) .typeDefinitionConfigurer(..) .typeVisitors(List.of(visitor)); // <3> ``` -------------------------------- ### Import map for GraphiQL dependencies Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql/src/main/resources/graphiql/index.html Import map for the GraphiQL page, mapping React, GraphiQL, and related packages to esm.sh URLs with integrity hashes for security. ```json { "imports": { "react": "https://esm.sh/react@19.2.7", "react/": "https://esm.sh/react@19.2.7/", "react-dom": "https://esm.sh/react-dom@19.2.7", "react-dom/": "https://esm.sh/react-dom@19.2.7/", "graphiql": "https://esm.sh/graphiql@5.2.4?standalone&external=react,react-dom,@graphiql/react,graphql", "graphiql/": "https://esm.sh/graphiql@5.2.4/", "@graphiql/plugin-explorer": "https://esm.sh/@graphiql/plugin-explorer@5.1.3?standalone&external=react,@graphiql/react,graphql", "@graphiql/react": "https://esm.sh/@graphiql/react@0.37.7?standalone&external=react,react-dom,graphql,@graphiql/toolkit,@emotion/is-prop-valid", "@graphiql/toolkit": "https://esm.sh/@graphiql/toolkit@0.12.1?standalone&external=graphql", "graphql": "https://esm.sh/graphql@17.0.2", "@emotion/is-prop-valid": "data:text/javascript," }, "integrity": { "https://esm.sh/react@19.2.7": "sha384-LO2cBox9zBA6AOWqno07582eanOcJxJyu4hwf3rg5CrZQ/XoPtgSAFlL6ezpFK0O", "https://esm.sh/react-dom@19.2.7": "sha384-upKKG1ShVOSXNAoNmdKSl8xWJl9L8fZ05Ki1rHXpPijT4hIS/FFh+88dxk72+jre", "https://esm.sh/graphiql@5.2.4": "sha384-3feoWeu5QZYyfhHQyP8i+VBW+tYf58tTwgBb8Fsrw2QlP/YRBR2tscNGcYyRDtHC", "https://esm.sh/graphiql@5.2.4?standalone&external=react,react-dom,@graphiql/react,graphql": "sha384-n1sWmquV8wXH/vbn5Q8BaQAw8iAFku5zAs2fPBrht0L/OP4/qgZWL/v/WhMLFPBH", "https://esm.sh/@graphiql/plugin-explorer@5.1.3": "sha384-aDt72jaNBi2he5K4f47qh+xnS6Za54L6vuoN6tKtToLAJfebp23zCaAl3zXGl7dV", "https://esm.sh/@graphiql/react@0.37.7?standalone&external=react,react-dom,graphql,@graphiql/toolkit,@emotion/is-prop-valid": "sha384-U8awo9eG6M8scx4fjis/pNfYja4d5EtxOFYcmvDGG8K4Rt/bGB6Km1hxbQXZr9qH", "https://esm.sh/@graphiql/toolkit@0.12.1?standalone&external=graphql": "sha384-+cNTwZgIW33q7A4E+ZoCMqzcXdfVIc2VthQvJ0uDpRXERBWYuDKPVMzvdQU8x48o", "https://esm.sh/graphql@17.0.2": "sha384-IPvlcmnvWT91sKqwbg9MxPXJUuPmSdwXCp22x6hcbBkAEhlfSKkMLR3v19K9iRUp" } } ``` -------------------------------- ### Basic @Controller with @QueryMapping Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Declares a @Controller with a @QueryMapping handler method that returns a String for the "hello" query. The method name determines the query name when not specified on the annotation. ```java @Controller public class GreetingController { @QueryMapping // <1> public String hello() { // <2> return "Hello, world!"; } } ``` -------------------------------- ### Java controller for interface schema mapping Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows a controller with a @QueryMapping for activities and a @SchemaMapping for the coordinator field on Activity. The coordinator method is called for any Activity subtype, as the mapping is replaced with multiple mappings for each implementing type. ```java @Controller public class ActivityController { @QueryMapping public List activities() { // ... } @SchemaMapping public User coordinator(Activity activity) { // Called for any Activity subtype } } ``` -------------------------------- ### Load GraphQL document by file name Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Java code that loads the document from 'projectReleases.graphql' and provides variable values. Uses the GraphQlClient builder to customize the DocumentSource for loading documents by names. ```java include::{include-java}/client/requests/documentsource/DocumentSource.java[tag=documentSource,indent=0] ``` -------------------------------- ### NamespaceConfiguration with GraphQlSourceBuilderCustomizer Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Configures runtime wiring with a GraphQlSourceBuilderCustomizer to declare wrapper types for the "Query" type. Lists wrapper fields ("music", "users") and manually declares data fetchers returning an empty Map for each. ```java @Configuration public class NamespaceConfiguration { @Bean public GraphQlSourceBuilderCustomizer customizer() { List queryWrappers = List.of("music", "users"); // <1> return (sourceBuilder) -> sourceBuilder.configureRuntimeWiring((wiringBuilder) -> queryWrappers.forEach((field) -> wiringBuilder.type("Query", (builder) -> builder.dataFetcher(field, (env) -> Collections.emptyMap()))) // <2> ); } } ``` -------------------------------- ### MusicController with @SchemaMapping and @QueryMapping Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc The source uses an include directive to reference an external file, so the actual code is not visible on this page. The surrounding text explains that the controller is annotated with @SchemaMapping and a typeName attribute, and defines a @QueryMapping for the "music" namespace. ```java include-code::MusicController[] ``` -------------------------------- ### Send fragment along query document Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Loads the document from 'projectReleases.graphql' and the fragment from 'releases.graphql', appending it to the document. ```java // include-code::TesterRequests[tag=fragment,indent=0] ``` -------------------------------- ### Execute subscription with direct response handling Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Uses executeSubscription for more control over subscription responses, handling each response directly instead of decoding from a single path. ```java include-code::ExecuteSubscription[tag=subscriptionExecute,indent=0] ``` -------------------------------- ### GraphQL document file projectReleases.graphql Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc GraphQL document file placed in src/main/resources/graphql-documents with .graphql or .gql extension. Referenced by file name when loading documents. ```graphql query projectReleases($slug: ID!) { project(slug: $slug) { name releases { version } } } ``` -------------------------------- ### Execute query with inline document Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Executes a query for a project and uses JsonPath to extract project release versions from the response. JsonPath is relative to the 'data' section. ```java // include-code::TesterRequests[tag=inlineDocument,indent=0] ``` -------------------------------- ### Maven build configuration for Querydsl Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Maven configuration for the maven-compiler-plugin with Querydsl annotation processor paths and generated sources directories. ```xml org.apache.maven.plugins maven-compiler-plugin com.querydsl querydsl-apt ${querydsl.version} jakarta jakarta.persistence jakarta.persistence-api target/generated-test-sources target/generated-sources ``` -------------------------------- ### @SchemaMapping with subtype-specific methods Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows how to define @SchemaMapping methods for a field, with a general method and a more specific one for a subtype (FooActivity). The general method is called for any Activity subtype except FooActivity, while the specific method handles FooActivity. ```java @SchemaMapping public User coordinator(Activity activity) { // Called for any Activity subtype except FooActivity } @SchemaMapping public User coordinator(FooActivity activity) { // ... } ``` -------------------------------- ### Test subscriptions with executeSubscription and StepVerifier Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Use executeSubscription instead of execute to obtain a stream of responses, then use StepVerifier from Project Reactor to inspect the stream. Subscriptions are supported only with WebSocketGraphQlTester, or with the server side ExecutionGraphQlService and WebGraphQlHandler extensions. ```java include-code::TestSubscriptions[tag=testSubscriptions,indent=0] ``` -------------------------------- ### Gradle build configuration for Querydsl Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Gradle configuration to add Querydsl annotation processor and set the annotation processor path. ```groovy dependencies { //... annotationProcessor "com.querydsl:querydsl-apt:$querydslVersion:jakarta", 'jakarta.persistence:jakarta.persistence-api' } compileJava { options.annotationProcessorPath = configurations.annotationProcessor } ``` -------------------------------- ### QuerydslDataFetcher with Projections Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Create a DataFetcher that uses Spring Data projections with Querydsl repositories. Define an Account domain class and an AccountProjection interface, then use QuerydslDataFetcher.builder().projectAs() to produce single or multi-result data fetchers. ```java class Account { String name, identifier, description; Person owner; } interface AccountProjection { String getName(); String getIdentifier(); } // For single result queries DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).single(); // For multi-result queries DataFetcher> dataFetcher = QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).many(); ``` -------------------------------- ### GraphQL client query for namespaced album Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Client query to fetch album data from the music namespace. ```graphql { music { album(id: 42) { id title } } } ``` -------------------------------- ### GraphiQL page styles Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql/src/main/resources/graphiql/index.html CSS rules to set the page margin to zero, make the GraphiQL container fill the viewport height, and center the loading indicator. ```css body { margin: 0; } #graphiql { height: 100dvh; } .loading { height: 100%; display: flex; align-items: center; justify-content: center; font-size: 4rem; } ``` -------------------------------- ### QueryByExampleDataFetcher Builder Usage Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Create DataFetchers for single, multi, and paginated queries using QueryByExampleDataFetcher.builder(). The builder uses the repository's QueryByExampleExecutor to fetch data based on the GraphQL arguments. ```java // For single result queries DataFetcher dataFetcher = QueryByExampleDataFetcher.builder(repository).single(); // For multi-result queries DataFetcher> dataFetcher = QueryByExampleDataFetcher.builder(repository).many(); // For paginated queries DataFetcher> dataFetcher = QueryByExampleDataFetcher.builder(repository).scrollable(); ``` -------------------------------- ### GraphQL query with fragment projectReleases.graphql Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc A GraphQL query document that uses a reusable '...releases' fragment in multiple queries. ```graphql query frameworkReleases { project(slug: "spring-framework") { name ...releases } } query graphqlReleases { project(slug: "spring-graphql") { name ...releases } } ``` -------------------------------- ### GraphQL schema with Query and Activity interface Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Schema definition with a Query type returning activities and an Activity interface implemented by FooActivity and BarActivity, each with an id and coordinator field of type User. ```graphql type Query { activities: [Activity!]! } interface Activity { id: ID! coordinator: User! } type FooActivity implements Activity { id: ID! coordinator: User! } type BarActivity implements Activity { id: ID! coordinator: User! } type User { name: String! } ``` -------------------------------- ### GraphQlTester builder configuration Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Configures common options for all transport builders: errorFilter, documentSource, and responseTimeout. ```java // include-code::GraphQlTesterBuilder[tag=inlineDocument,indent=0] ``` -------------------------------- ### Configure FederationSchemaFactory bean Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/federation.adoc Enable the federation integration by declaring a FederationSchemaFactory bean and plugging it into GraphQlSource.Builder via a GraphQlSourceBuilderCustomizer. This configuration is for Spring Boot. ```java @Configuration public class FederationConfig { @Bean public GraphQlSourceBuilderCustomizer customizer(FederationSchemaFactory factory) { return builder -> builder.schemaFactory(factory::createGraphQLSchema); } @Bean public FederationSchemaFactory schemaFactory() { return new FederationSchemaFactory(); } } ``` -------------------------------- ### Execute and verify mutation Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Use executeAndVerify instead of execute to verify there are no errors in the response when a request does not have any response data, e.g., a mutation. ```java graphQlTester.query(query).executeAndVerify(); ``` -------------------------------- ### GraphQL schema for interface Activity with implementations Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Defines a Query type with an activities field returning a list of Activity, an Activity interface with id and coordinator fields, and two implementations FooActivity and BarActivity. This schema is used to demonstrate interface schema mappings. ```graphql type Query { activities: [Activity!]! } interface Activity { id: ID! coordinator: User! } type FooActivity implements Activity { id: ID! coordinator: User! } type BarActivity implements Activity { id: ID! coordinator: User! } type User { name: String! } ``` -------------------------------- ### GraphQL query document projectReleases.graphql Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc A GraphQL query document that can be placed under 'graphql-test/' on the classpath and referred to by file name. ```graphql query projectReleases($slug: ID!) { project(slug: $slug) { releases { version } } } ``` -------------------------------- ### @BatchMapping method for author field Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Replaces the boilerplate @SchemaMapping delegation with a @BatchMapping method that returns a Mono>. Book must implement hashcode and equals to be used as a unique key. ```java @Controller public class BookController { @BatchMapping public Mono> author(List books) { // ... } } ``` -------------------------------- ### Enable schema mapping inspection with inspectSchemaMappings Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Customize GraphQlSource.Builder to enable schema inspection. The report is logged but can be handled as needed. The report includes unmapped fields, registrations, arguments, and nullness errors. ```java GraphQlSource.Builder builder = ... builder.schemaResources(..) .inspectSchemaMappings(report -> { logger.debug(report); }); ``` ```text GraphQL schema inspection: Unmapped fields: {Book=[title], Author[firstName, lastName]} // <1> Unmapped registrations: {Book.reviews=BookController#reviews[1 args]} <2> Unmapped arguments: {BookController#bookSearch[1 args]=[myAuthor]} // <3> Field nullness errors: {Book=[title is NON_NULL -> 'Book#title' is NULLABLE]} <4> Argument nullness errors: {BookController#bookById[1 args]=[java.lang.String id should be NULLABLE]} <5> Skipped types: [BookOrAuthor] // <6> ``` -------------------------------- ### Schema include for friends and beverages Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Schema for the batch loading recipes section, defining friends and beverages. This is an include directive that references an external file; the actual schema content is not shown on this page. ```graphql include::ROOT:{include-resources}/execution/batching/recipes/friendsAndBeverages.graphqls[] ``` -------------------------------- ### Configure PreparsedDocumentProvider via GraphQlSource.Builder Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Registers a PreparsedDocumentProvider for operation caching. Typically accessed through Spring Boot's GraphQlSourceBuilderCustomizer. The provider caches parsed documents to avoid re-parsing and validation. ```java // Typically, accessed through Spring Boot's GraphQlSourceBuilderCustomizer GraphQlSource.Builder builder = ... // Create provider PreparsedDocumentProvider provider = new ApolloPersistedQuerySupport(new InMemoryPersistedQueryCache(Collections.emptyMap())); builder.schemaResources(..) .configureRuntimeWiring(..) .configureGraphQl(graphQLBuilder -> graphQLBuilder.preparsedDocumentProvider(provider)) ``` -------------------------------- ### Execute method for sync and non-blocking clients Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Shows the synchronous and non-blocking variants of the execute method for handling GraphQL responses with more control than retrieve. The sync variant uses the blocking client, while the non-blocking variant uses the reactive client. ```java include::{include-java}/client/requests/execute/Execute.java[tag=executeSync,indent=0] ``` ```java include::{include-java}/client/requests/execute/Execute.java[tag=execute,indent=0] ``` -------------------------------- ### Batch load federated entities with @EntityMapping and @BatchMapping Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/federation.adoc Load federated entities of the same type together by accepting a List of ids and returning a List or Flux of entities. The idList naming convention helps de-pluralize the parameter name; @BatchMapping handles the rest of the graph. ```java @Controller private static class BookController { @EntityMapping public List book(@Argument List idList) { // <1> // ... return books in the same order } @BatchMapping public Map author(List books) { // <2> // ... } } ``` -------------------------------- ### Load federated entities with DataLoader Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/federation.adoc Load federated entities with a DataLoader by registering a batch loader for the entity type and declaring a DataLoader argument to the @EntityMapping method. @BatchMapping methods handle the rest of the graph. ```java @Controller private static class BookController { @Autowired public DataLoaderBookController(BatchLoaderRegistry registry) { // <1> registry.forTypePair(Integer.class, Book.class).registerBatchLoader((bookIds, environment) -> { // load entities... }); } @EntityMapping public Future book(@Argument int id, DataLoader dataLoader) { // <2> return dataLoader.load(id); } @BatchMapping public Map author(List books) { // <3> // ... } } ``` -------------------------------- ### Add spring-graphql-test dependency with Gradle Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Add the spring-graphql-test dependency to your Gradle build for testing support. ```groovy dependencies { // ... testImplementation 'org.springframework.graphql:spring-graphql-test:{spring-graphql-version}' } ``` -------------------------------- ### Generated connection types Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Shows the connection, edge, and pageInfo types that the ConnectionTypeDefinitionConfigurer adds to the schema. ```graphql type BookConnection { edges: [BookEdge]! pageInfo: PageInfo! } type BookEdge { node: Book! cursor: String! } type PageInfo { hasPreviousPage: Boolean! hasNextPage: Boolean! startCursor: String endCursor: String } ``` -------------------------------- ### Configure ConnectionAdapter with ConnectionFieldTypeVisitor Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Configures a ConnectionAdapter via a ConnectionFieldTypeVisitor. The visitor is registered as a type visitor to adapt container types to Connection. Built-in adapters exist for Spring Data's Window and Slice. ```java ConnectionAdapter adapter = ... ; GraphQLTypeVisitor visitor = ConnectionFieldTypeVisitor.create(List.of(adapter)) // <1> GraphQlSource.schemaResourceBuilder() .schemaResources(..) .typeDefinitionConfigurer(..) .typeVisitors(List.of(visitor)) // <2> ``` -------------------------------- ### Controller with @BatchMapping for individual subtype Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Java controller showing how to override the batch mapping for a specific subtype (FooActivity) using the field attribute of @BatchMapping. ```java @Controller public class BookController { @QueryMapping public List activities() { // ... } @BatchMapping Map coordinator(List activities) { // Called for all Activity subtypes } @BatchMapping(field = "coordinator") Map fooCoordinator(List activities) { // ... } } ``` -------------------------------- ### Retrieve data synchronously with GraphQlClient.retrieve Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc This code block is included from the Retrieve.java file and shows how to perform a synchronous retrieve request. It is part of the 'Sync' tab in the documentation. ```java include::{include-java}/client/requests/retrieve/Retrieve.java[tag=retrieveSync,indent=0] ``` -------------------------------- ### Define paginated query with BookConnection Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Defines a GraphQL schema with a paginated query. The ConnectionTypeDefinitionConfigurer automatically adds the required connection and edge types at startup if not explicitly declared. ```graphql type Query { books(first:Int, after:String, last:Int, before:String): BookConnection } type Book { id: ID! title: String! } ``` -------------------------------- ### @Argument with Map Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Shows how to use @Argument with a Map to obtain the raw argument value. Note that prior to 1.2, this returned the full arguments map when no name was specified; after 1.2, it always returns the raw value for the argument. ```java @Controller public class BookController { @MutationMapping public Book addBook(@Argument Map bookInput) { // ... } } ``` -------------------------------- ### SyncGraphQlClientInterceptor for blocking transports Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Creates a SyncGraphQlClientInterceptor for blocking transports created with GraphQlClient.SyncBuilder to intercept all requests. ```java include-code::SyncInterceptor[] ``` -------------------------------- ### Custom ExecutionStrategy with DataFetcherExceptionHandler Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Creates a custom ExecutionStrategy using a DataFetcherExceptionHandler built from DataFetcherExceptionResolvers. Registers it via GraphQlSourceBuilderCustomizer to set query and mutation execution strategies. ```java @Bean GraphQlSourceBuilderCustomizer sourceBuilderCustomizer( ObjectProvider resolvers) { DataFetcherExceptionHandler exceptionHandler = DataFetcherExceptionResolver.createExceptionHandler(resolvers.stream().toList()); AsyncExecutionStrategy strategy = new CustomAsyncExecutionStrategy(exceptionHandler); return sourceBuilder -> sourceBuilder.configureGraphQl(builder -> builder.queryExecutionStrategy(strategy).mutationExecutionStrategy(strategy)); } ``` -------------------------------- ### RuntimeWiringConfigurer with scalar and directive wiring Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/request-execution.adoc Registers a RuntimeWiringConfigurer bean that adds a scalar type and directive wiring to the RuntimeWiring.Builder. Use this to customize the GraphQL schema wiring in a Spring configuration. ```java @Bean public RuntimeWiringConfigurer runtimeWiringConfigurer(BookRepository repository) { GraphQLScalarType scalarType = ... ; SchemaDirectiveWiring directiveWiring = ... ; return wiringBuilder -> wiringBuilder .scalar(scalarType) .directiveWiring(directiveWiring); } } ``` -------------------------------- ### Verify error exists with expect Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Use expect instead of filter to verify that an error does exist, and throw an assertion error if it doesn't. ```java include-code::TestErrors[tag=expectedErrors,indent=0] ``` -------------------------------- ### Add spring-graphql-test dependency with Maven Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc Add the spring-graphql-test dependency to your Maven build for testing support. ```xml org.springframework.graphql spring-graphql-test {spring-graphql-version} test ``` -------------------------------- ### GraphQL fragment releases.graphql Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/testing.adoc A reusable fragment definition that can be loaded from a separate file and appended to a query document. ```graphql fragment releases on Project { releases { version } } ``` -------------------------------- ### GraphQlClientInterceptor for non-blocking transports Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Creates a GraphQlClientInterceptor for non-blocking transports created with GraphQlClient.Builder to intercept all requests. ```java include-code::MyInterceptor[] ``` -------------------------------- ### Declare a repository as QuerydslPredicateExecutor Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Declares an AccountRepository that extends Repository and QuerydslPredicateExecutor to enable Querydsl support. ```java public interface AccountRepository extends Repository, QuerydslPredicateExecutor { } ``` -------------------------------- ### Register interceptor with client builder Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/client.adoc Registers the interceptor through the client builder after creating it. ```java include-code::UseInterceptor[tag=register,indent=0] ``` -------------------------------- ### GraphQL namespaced schema definition Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc JSON schema definition for namespacing with MusicQueries and UserQueries types nested under Query, allowing queries like album. ```json include::ROOT:{include-resources}/controllers/namespaces.graphqls[] ``` -------------------------------- ### BatchLoaderRegistry mapped batch loader Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Registers a mapped batch loader for Author by Book IDs, returning a Map. The @SchemaMapping method delegates to the DataLoader. ```java public BookController(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Map }); } @SchemaMapping public CompletableFuture author(Book book, DataLoader loader) { return loader.load(book.getAuthorId()); } } ``` -------------------------------- ### BatchLoaderRegistry registration and DataLoader usage in @SchemaMapping Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/controllers.adoc Registers a mapped batch loader for Author entities and uses a DataLoader in a @SchemaMapping method to load authors by ID. The DataLoader method argument is resolved by generic type, with the method argument name as a fallback. ```java public BookController(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Map }); } @SchemaMapping public CompletableFuture author(Book book, DataLoader loader) { return loader.load(book.getAuthorId()); } ``` -------------------------------- ### Programmatic Transactional Controller Method Source: https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-docs/modules/ROOT/pages/data.adoc Use TransactionOperations to programmatically manage transactions within a @MutationMapping method. This gives explicit control over transaction boundaries. ```java @Controller public class AccountController { private final TransactionOperations transactionOperations; @MutationMapping public Account addAccount(@Argument AccountInput input) { return transactionOperations.execute(status -> { // ... }); } } ```