5. Data Integration

Spring for GraphQL lets you leverage existing Spring technology, following common programming models to expose underlying data sources through GraphQL.spring-doc.cn

This section discusses an integration layer for Spring Data that provides an easy way to adapt a Querydsl or a Query by Example repository to a DataFetcher, including the option for automated detection and GraphQL Query registration for repositories marked with @GraphQlRepository.spring-doc.cn

5.1. Querydsl

Spring for GraphQL supports use of Querydsl to fetch data through the Spring Data Querydsl extension. Querydsl provides a flexible yet typesafe approach to express query predicates by generating a meta-model using annotation processors.spring-doc.cn

For example, declare a repository as QuerydslPredicateExecutor:spring-doc.cn

public interface AccountRepository extends Repository<Account, Long>,
            QuerydslPredicateExecutor<Account> {
}

Then use it to create a DataFetcher:spring-doc.cn

// For single result queries
DataFetcher<Account> dataFetcher =
        QuerydslDataFetcher.builder(repository).single();

// For multi-result queries
DataFetcher<Iterable<Account>> dataFetcher =
        QuerydslDataFetcher.builder(repository).many();

You can now register the above DataFetcher through a RuntimeWiringConfigurer.spring-doc.cn

The DataFetcher builds a Querydsl Predicate from GraphQL request parameters, and uses it to fetch data. Spring Data supports QuerydslPredicateExecutor for JPA, MongoDB, and LDAP.spring-doc.cn

If the repository is ReactiveQuerydslPredicateExecutor, the builder returns DataFetcher<Mono<Account>> or DataFetcher<Flux<Account>>. Spring Data supports this variant for MongoDB.spring-doc.cn

5.1.1. Build Setup

To configure Querydsl in your build, follow the official reference documentation:spring-doc.cn

For example:spring-doc.cn

Gradle
dependencies {
    //...

    annotationProcessor "com.querydsl:querydsl-apt:$querydslVersion:jpa",
            'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final',
            'javax.annotation:javax.annotation-api:1.3.2'
}

compileJava {
     options.annotationProcessorPath = configurations.annotationProcessor
}
Maven
<dependencies>
    <!-- ... -->
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>${querydsl.version}</version>
        <classifier>jpa</classifier>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.2.Final</version>
    </dependency>
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>javax.annotation-api</artifactId>
        <version>1.3.2</version>
    </dependency>
</dependencies>
<plugins>
    <!-- Annotation processor configuration -->
    <plugin>
        <groupId>com.mysema.maven</groupId>
        <artifactId>apt-maven-plugin</artifactId>
        <version>${apt-maven-plugin.version}</version>
        <executions>
            <execution>
                <goals>
                    <goal>process</goal>
                </goals>
                <configuration>
                    <outputDirectory>target/generated-sources/java</outputDirectory>
                    <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>

The webmvc-http sample uses Querydsl for artifactRepositories.spring-doc.cn

5.1.2. Customizations

QuerydslDataFetcher supports customizing how GraphQL arguments are bound onto properties to create a Querydsl Predicate. By default, arguments are bound as "is equal to" for each available property. To customize that, you can use QuerydslDataFetcher builder methods to provide a QuerydslBinderCustomizer.spring-doc.cn

A repository may itself be an instance of QuerydslBinderCustomizer. This is auto-detected and transparently applied during Auto-Registration. However, when manually building a QuerydslDataFetcher you will need to use builder methods to apply it.spring-doc.cn

QuerydslDataFetcher supports interface and DTO projections to transform query results before returning these for further GraphQL processing.spring-doc.cn

To learn what projections are, please refer to the Spring Data docs. To understand how to use projections in GraphQL, please see Selection Set vs Projections.

To use Spring Data projections with Querydsl repositories, create either a projection interface or a target DTO class and configure it through the projectAs method to obtain a DataFetcher producing the target type:spring-doc.cn

class Account {

    String name, identifier, description;

    Person owner;
}

interface AccountProjection {

    String getName();

    String getIdentifier();
}

// For single result queries
DataFetcher<AccountProjection> dataFetcher =
        QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).single();

// For multi-result queries
DataFetcher<Iterable<AccountProjection>> dataFetcher =
        QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).many();

5.1.3. Auto-Registration

If a repository is annotated with @GraphQlRepository, it is automatically registered for queries that do not already have a registered DataFetcher and whose return type matches that of the repository domain type. This includes both single value and multi-value queries.spring-doc.cn

By default, the name of the GraphQL type returned by the query must match the simple name of the repository domain type. If needed, you can use the typeName attribute of @GraphQlRepository to specify the target GraphQL type name.spring-doc.cn

Auto-registration detects if a given repository implements QuerydslBinderCustomizer and transparently applies that through QuerydslDataFetcher builder methods.spring-doc.cn

Auto-registration is performed through a built-in RuntimeWiringConfigurer that can be obtained from QuerydslDataFetcher. The Boot starter automatically detects @GraphQlRepository beans and uses them to initialize the RuntimeWiringConfigurer with.spring-doc.cn

Auto-registration does not support customizations. If you need that, you’ll need to use QueryByExampleDataFetcher to build and register the DataFetcher manually through a RuntimeWiringConfigurer.spring-doc.cn

5.2. Query by Example

Spring Data supports the use of Query by Example to fetch data. Query by Example (QBE) is a simple querying technique that does not require you to write queries through store-specific query languages.spring-doc.cn

Start by declaring a repository that is QueryByExampleExecutor:spring-doc.cn

public interface AccountRepository extends Repository<Account, Long>,
            QueryByExampleExecutor<Account> {
}

Use QueryByExampleDataFetcher to turn the repository into a DataFetcher:spring-doc.cn

// For single result queries
DataFetcher<Account> dataFetcher =
        QueryByExampleDataFetcher.builder(repository).single();

// For multi-result queries
DataFetcher<Iterable<Account>> dataFetcher =
        QueryByExampleDataFetcher.builder(repository).many();

You can now register the above DataFetcher through a RuntimeWiringConfigurer.spring-doc.cn

The DataFetcher uses the GraphQL arguments map to create the domain type of the repository and use that as the example object to fetch data with. Spring Data supports QueryByExampleDataFetcher for JPA, MongoDB, Neo4j, and Redis.spring-doc.cn

If the repository is ReactiveQueryByExampleExecutor, the builder returns DataFetcher<Mono<Account>> or DataFetcher<Flux<Account>>. Spring Data supports this variant for MongoDB, Neo4j, Redis, and R2dbc.spring-doc.cn

5.2.1. Build Setup

Query by Example is already included in the Spring Data modules for the data stores where it is supported, so no extra setup is required to enable it.spring-doc.cn

5.2.2. Customizations

QueryByExampleDataFetcher supports interface and DTO projections to transform query results before returning these for further GraphQL processing.spring-doc.cn

To learn what projections are, please refer to the Spring Data documentation. To understand the role of projections in GraphQL, please see Selection Set vs Projections.

To use Spring Data projections with Query by Example repositories, create either a projection interface or a target DTO class and configure it through the projectAs method to obtain a DataFetcher producing the target type:spring-doc.cn

class Account {

    String name, identifier, description;

    Person owner;
}

interface AccountProjection {

    String getName();

    String getIdentifier();
}

// For single result queries
DataFetcher<AccountProjection> dataFetcher =
        QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).single();

// For multi-result queries
DataFetcher<Iterable<AccountProjection>> dataFetcher =
        QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).many();

5.2.3. Auto-Registration

If a repository is annotated with @GraphQlRepository, it is automatically registered for queries that do not already have a registered DataFetcher and whose return type matches that of the repository domain type. This includes both single value and multi-value queries.spring-doc.cn

By default, the name of the GraphQL type returned by the query must match the simple name of the repository domain type. If needed, you can use the typeName attribute of @GraphQlRepository to specify the target GraphQL type name.spring-doc.cn

Auto-registration is performed through a built-in RuntimeWiringConfigurer that can be obtained from QueryByExampleDataFetcher. The Boot starter automatically detects @GraphQlRepository beans and uses them to initialize the RuntimeWiringConfigurer with.spring-doc.cn

Auto-registration does not support customizations. If you need that, you’ll need to use QueryByExampleDataFetcher to build and register the DataFetcher manually through a RuntimeWiringConfigurer.spring-doc.cn

5.3. Selection Set vs Projections

A common question that arises is, how GraphQL selection sets compare to Spring Data projections and what role does each play?spring-doc.cn

The short answer is that Spring for GraphQL is not a data gateway that translates GraphQL queries directly into SQL or JSON queries. Instead, it lets you leverage existing Spring technology and does not assume a one for one mapping between the GraphQL schema and the underlying data model. That is why client-driven selection and server-side transformation of the data model can play complementary roles.spring-doc.cn

To better understand, consider that Spring Data promotes domain-driven (DDD) design as the recommended approach to manage complexity in the data layer. In DDD, it is important to adhere to the constraints of an aggregate. By definition an aggregate is valid only if loaded in its entirety, since a partially loaded aggregate may impose limitations on aggregate functionality.spring-doc.cn

In Spring Data you can choose whether you want your aggregate be exposed as is, or whether to apply transformations to the data model before returning it as a GraphQL result. Sometimes it’s enough to do the former, and by default the Querydsl and the Query by Example integrations turn the GraphQL selection set into property path hints that the underlying Spring Data module uses to limit the selection.spring-doc.cn

In other cases, it’s useful to reduce or even transform the underlying data model in order to adapt to the GraphQL schema. Spring Data supports this through Interface and DTO Projections.spring-doc.cn

Interface projections define a fixed set of properties to expose where properties may or may not be null, depending on the data store query result. There are two kinds of interface projections both of which determine what properties to load from the underlying data source:spring-doc.cn

DTO projections offer a higher level of customization as you can place transformation code either in the constructor or in getter methods.spring-doc.cn

DTO projections materialize from a query where the individual properties are determined by the projection itself. DTO projections are commonly used with full-args constructors (e.g. Java records), and therefore they can only be constructed if all required fields (or columns) are part of the database query result.spring-doc.cn