Add graphql-dataloader: Spring GraphQL 2.0 DataLoader batching vs naive N+1, and non-null propagation on a dangling FK
- naive @SchemaMapping resolver: 6 statements (5 books/5 authors), 21 statements (20 books/5 authors) - batched @BatchMapping resolver: flat 2 statements in both cases, via DataLoader + .distinct() - dangling authorId nulls the entire GraphQL response via non-null propagation, byte-identical under both resolver strategies - 6-test suite over real HTTP against a live embedded Tomcat instance, SQL captured via a JDK dynamic proxy (StatementLoggingDataSource, reused from sdjpa4-demo) - docs/05: two Boot 4.1 packaging changes hit along the way (DataSourceAutoConfiguration's new package, Jackson 3 by default) - root README: add row for graphql-dataloader; fix openapi-versioning's placeholder link now that post 7477 is live
This commit is contained in:
+42
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.graphqldataloader;
|
||||
|
||||
import com.ankurm.graphqldataloader.support.SqlLog;
|
||||
import com.ankurm.graphqldataloader.support.StatementLoggingDataSource;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
|
||||
public class GraphqlDataloaderApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(GraphqlDataloaderApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SqlLog sqlLog() {
|
||||
return new SqlLog();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource(SqlLog sqlLog) {
|
||||
// A random suffix per context, not a fixed name: DB_CLOSE_DELAY=-1 keeps an H2 in-memory
|
||||
// database alive for as long as this JVM runs, so a fixed name would leak across separate
|
||||
// Spring ApplicationContexts started in the same test JVM (e.g. the "naive" and "batched"
|
||||
// profile test classes each boot their own context) and the second one to run schema.sql
|
||||
// would fail with "Table already exists" against the first one's still-open database.
|
||||
String dbName = "graphqldataloader-" + java.util.UUID.randomUUID();
|
||||
HikariDataSource real = DataSourceBuilder.create()
|
||||
.url("jdbc:h2:mem:" + dbName + ";DB_CLOSE_DELAY=-1")
|
||||
.username("sa")
|
||||
.password("")
|
||||
.type(HikariDataSource.class)
|
||||
.build();
|
||||
return StatementLoggingDataSource.wrap(real, sqlLog);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ankurm.graphqldataloader.domain;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "AUTHOR")
|
||||
public class Author {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
protected Author() {
|
||||
}
|
||||
|
||||
public Author(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.ankurm.graphqldataloader.domain;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface AuthorRepository extends JpaRepository<Author, Long> {
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.ankurm.graphqldataloader.domain;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
/**
|
||||
* Deliberately NOT a JPA {@code @ManyToOne} to {@link Author} — {@code authorId} is a plain
|
||||
* column. The whole point of this module is controlling, and observing, exactly how and when
|
||||
* the Author for a Book gets loaded from a GraphQL resolver, not letting Hibernate's own lazy
|
||||
* loading decide that for us underneath a completely different mechanism.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "BOOK")
|
||||
public class Book {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
private Long authorId;
|
||||
|
||||
protected Book() {
|
||||
}
|
||||
|
||||
public Book(String title, Long authorId) {
|
||||
this.title = title;
|
||||
this.authorId = authorId;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public Long getAuthorId() {
|
||||
return authorId;
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.ankurm.graphqldataloader.domain;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface BookRepository extends JpaRepository<Book, Long> {
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.graphqldataloader.resolver;
|
||||
|
||||
import com.ankurm.graphqldataloader.domain.Author;
|
||||
import com.ankurm.graphqldataloader.domain.AuthorRepository;
|
||||
import com.ankurm.graphqldataloader.domain.Book;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.graphql.data.method.annotation.BatchMapping;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Same field, same schema, one annotation different: {@code @BatchMapping} instead of
|
||||
* {@code @SchemaMapping}, and the method signature takes every {@code Book} GraphQL Java is about
|
||||
* to resolve {@code author} for in this batch, not one. Spring GraphQL wires this into a
|
||||
* per-request {@code DataLoader} automatically — no {@code BatchLoaderRegistry} bean needed for
|
||||
* this shortcut form. See docs/03-the-batchmapping-fix.md.
|
||||
*
|
||||
* <p>The returned {@code Map} deliberately omits an entry for any {@code Book} whose author
|
||||
* lookup misses (a dangling {@code authorId}) rather than putting a null value in — Spring
|
||||
* GraphQL treats a missing key the same as an explicit null for that source object, which is
|
||||
* what docs/05-the-null-propagation-trap.md is built around.
|
||||
*/
|
||||
@Profile("batched")
|
||||
@Controller
|
||||
public class BatchedAuthorResolver {
|
||||
|
||||
private final AuthorRepository authorRepository;
|
||||
|
||||
public BatchedAuthorResolver(AuthorRepository authorRepository) {
|
||||
this.authorRepository = authorRepository;
|
||||
}
|
||||
|
||||
@BatchMapping(typeName = "Book", field = "author")
|
||||
public Map<Book, Author> author(List<Book> books) {
|
||||
List<Long> authorIds = books.stream().map(Book::getAuthorId).distinct().toList();
|
||||
Map<Long, Author> byId = authorRepository.findAllById(authorIds).stream()
|
||||
.collect(Collectors.toMap(Author::getId, a -> a));
|
||||
|
||||
Map<Book, Author> result = new HashMap<>();
|
||||
for (Book book : books) {
|
||||
Author author = byId.get(book.getAuthorId());
|
||||
if (author != null) {
|
||||
result.put(book, author);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.ankurm.graphqldataloader.resolver;
|
||||
|
||||
import com.ankurm.graphqldataloader.domain.Book;
|
||||
import com.ankurm.graphqldataloader.domain.BookRepository;
|
||||
import org.springframework.graphql.data.method.annotation.QueryMapping;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Controller
|
||||
public class BookController {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
public BookController(BookRepository bookRepository) {
|
||||
this.bookRepository = bookRepository;
|
||||
}
|
||||
|
||||
@QueryMapping
|
||||
public List<Book> books() {
|
||||
return bookRepository.findAll();
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.ankurm.graphqldataloader.resolver;
|
||||
|
||||
import com.ankurm.graphqldataloader.domain.Author;
|
||||
import com.ankurm.graphqldataloader.domain.AuthorRepository;
|
||||
import com.ankurm.graphqldataloader.domain.Book;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.graphql.data.method.annotation.SchemaMapping;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
/**
|
||||
* The resolver nobody would flag in review: one {@code @SchemaMapping} method, one repository
|
||||
* call, correct output. GraphQL Java calls it once per {@code Book} in the result, independently,
|
||||
* which is exactly how it becomes N+1 — see docs/02-the-n-plus-one-problem.md.
|
||||
*/
|
||||
@Profile("naive")
|
||||
@Controller
|
||||
public class NaiveAuthorResolver {
|
||||
|
||||
private final AuthorRepository authorRepository;
|
||||
|
||||
public NaiveAuthorResolver(AuthorRepository authorRepository) {
|
||||
this.authorRepository = authorRepository;
|
||||
}
|
||||
|
||||
@SchemaMapping(typeName = "Book", field = "author")
|
||||
public Author author(Book book) {
|
||||
return authorRepository.findById(book.getAuthorId()).orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ankurm.graphqldataloader.support;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Thread-safe record of every SQL statement actually executed, since the last {@link #reset()}. */
|
||||
public class SqlLog {
|
||||
|
||||
private final List<String> statements = new CopyOnWriteArrayList<>();
|
||||
|
||||
public void record(String sql) {
|
||||
statements.add(sql);
|
||||
}
|
||||
|
||||
public List<String> all() {
|
||||
return Collections.unmodifiableList(statements);
|
||||
}
|
||||
|
||||
public int count() {
|
||||
return statements.size();
|
||||
}
|
||||
|
||||
public long countContaining(String needle) {
|
||||
return statements.stream().filter(s -> s.contains(needle)).count();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
statements.clear();
|
||||
}
|
||||
|
||||
public String render() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int i = 1;
|
||||
for (String s : statements) {
|
||||
sb.append(i++).append(". ").append(s).append('\n');
|
||||
}
|
||||
sb.append("\ntotal statements: ").append(statements.size());
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String renderNumbered() {
|
||||
return statements.stream()
|
||||
.map(s -> (statements.indexOf(s) + 1) + ". " + s)
|
||||
.collect(Collectors.joining("\n"));
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.ankurm.graphqldataloader.support;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
/**
|
||||
* A {@link DataSource} decorator that logs every SQL statement actually sent to the driver, via
|
||||
* a JDK dynamic proxy over {@link Connection} and {@link Statement}/{@link PreparedStatement} —
|
||||
* so counts reflect what really reached the database, not what Hibernate's own SQL logging
|
||||
* chooses to print (which, notably, prints one line per {@code addBatch()} call rather than
|
||||
* counting {@code executeBatch()} as the single round trip it is). Same mechanism used in the
|
||||
* sdjpa4-demo companion project for "Spring Data JDBC vs Spring Data JPA in 2026".
|
||||
*/
|
||||
public class StatementLoggingDataSource implements InvocationHandler {
|
||||
|
||||
private final DataSource delegate;
|
||||
private final SqlLog log;
|
||||
|
||||
private StatementLoggingDataSource(DataSource delegate, SqlLog log) {
|
||||
this.delegate = delegate;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
public static DataSource wrap(DataSource delegate, SqlLog log) {
|
||||
return (DataSource) Proxy.newProxyInstance(
|
||||
DataSource.class.getClassLoader(),
|
||||
new Class<?>[]{DataSource.class},
|
||||
new StatementLoggingDataSource(delegate, log));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
Object result;
|
||||
try {
|
||||
result = method.invoke(delegate, args);
|
||||
} catch (java.lang.reflect.InvocationTargetException e) {
|
||||
throw e.getCause();
|
||||
}
|
||||
if ("getConnection".equals(method.getName()) && result instanceof Connection connection) {
|
||||
return wrapConnection(connection);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Connection wrapConnection(Connection connection) {
|
||||
return (Connection) Proxy.newProxyInstance(
|
||||
Connection.class.getClassLoader(),
|
||||
new Class<?>[]{Connection.class},
|
||||
(proxy, method, args) -> {
|
||||
Object result;
|
||||
try {
|
||||
result = method.invoke(connection, args);
|
||||
} catch (java.lang.reflect.InvocationTargetException e) {
|
||||
throw e.getCause();
|
||||
}
|
||||
String name = method.getName();
|
||||
if ("prepareStatement".equals(name) && args != null && args.length > 0 && result instanceof PreparedStatement ps) {
|
||||
return wrapPreparedStatement(ps, (String) args[0]);
|
||||
}
|
||||
if ("createStatement".equals(name) && result instanceof Statement st) {
|
||||
return wrapStatement(st);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
private PreparedStatement wrapPreparedStatement(PreparedStatement ps, String sql) {
|
||||
return (PreparedStatement) Proxy.newProxyInstance(
|
||||
PreparedStatement.class.getClassLoader(),
|
||||
new Class<?>[]{PreparedStatement.class},
|
||||
(proxy, method, args) -> {
|
||||
String name = method.getName();
|
||||
if (name.startsWith("execute")) {
|
||||
log.record(sql.trim());
|
||||
}
|
||||
try {
|
||||
return method.invoke(ps, args);
|
||||
} catch (java.lang.reflect.InvocationTargetException e) {
|
||||
throw e.getCause();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Statement wrapStatement(Statement st) {
|
||||
return (Statement) Proxy.newProxyInstance(
|
||||
Statement.class.getClassLoader(),
|
||||
new Class<?>[]{Statement.class},
|
||||
(proxy, method, args) -> {
|
||||
String name = method.getName();
|
||||
if (name.startsWith("execute") && args != null && args.length > 0 && args[0] instanceof String sql) {
|
||||
log.record(sql.trim());
|
||||
}
|
||||
try {
|
||||
return method.invoke(st, args);
|
||||
} catch (java.lang.reflect.InvocationTargetException e) {
|
||||
throw e.getCause();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
spring:
|
||||
application:
|
||||
name: graphql-dataloader
|
||||
sql:
|
||||
init:
|
||||
mode: always
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: none
|
||||
open-in-view: false
|
||||
properties:
|
||||
hibernate:
|
||||
show_sql: false # real statements come from StatementLoggingDataSource instead
|
||||
graphql:
|
||||
graphiql:
|
||||
enabled: true
|
||||
|
||||
logging:
|
||||
level:
|
||||
root: WARN
|
||||
com.ankurm.graphqldataloader: INFO
|
||||
@@ -0,0 +1,14 @@
|
||||
type Query {
|
||||
books: [Book!]!
|
||||
}
|
||||
|
||||
type Book {
|
||||
id: ID!
|
||||
title: String!
|
||||
author: Author!
|
||||
}
|
||||
|
||||
type Author {
|
||||
id: ID!
|
||||
name: String!
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
create table author (
|
||||
id bigint auto_increment primary key,
|
||||
name varchar(200) not null
|
||||
);
|
||||
|
||||
create table book (
|
||||
id bigint auto_increment primary key,
|
||||
title varchar(200) not null,
|
||||
author_id bigint
|
||||
);
|
||||
Reference in New Issue
Block a user