rejected(DataIntegrityViolationException e) {
+ String reason = e.getMostSpecificCause().getMessage();
+ return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(new ApiError("IMPORT_REJECTED",
+ "Nothing was imported: the database refused a row. " + firstLine(reason), null));
+ }
+
+ private static String firstLine(String text) {
+ return text == null ? "" : text.lines().findFirst().orElse("");
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/BatchingApplication.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/BatchingApplication.java
new file mode 100644
index 0000000..29f0898
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/BatchingApplication.java
@@ -0,0 +1,12 @@
+package com.amigoscode.batching;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class BatchingApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(BatchingApplication.class, args);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/ManagedEntities.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/ManagedEntities.java
new file mode 100644
index 0000000..107e080
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/ManagedEntities.java
@@ -0,0 +1,39 @@
+package com.amigoscode.batching.db;
+
+import java.util.Iterator;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.hibernate.Interceptor;
+
+/**
+ * Remembers the largest number of entities the persistence context held at any flush. Every
+ * entity Hibernate manages stays in memory, with a snapshot of its values for dirty checking,
+ * until the transaction ends or someone calls clear(). This makes that number visible.
+ *
+ * Switched on in application.properties with hibernate.session_factory.interceptor. Hibernate
+ * calls preFlush with every entity in the persistence context, right before each flush.
+ *
+ *
A teaching tool: do not ship a static, shared counter like this in a real application.
+ */
+public class ManagedEntities implements Interceptor {
+
+ private static final AtomicInteger PEAK = new AtomicInteger();
+
+ @Override
+ public void preFlush(Iterator entities) {
+ int count = 0;
+ while (entities.hasNext()) {
+ entities.next();
+ count++;
+ }
+ PEAK.accumulateAndGet(count, Math::max);
+ }
+
+ public static void reset() {
+ PEAK.set(0);
+ }
+
+ /** The most entities the persistence context held at a flush since the last reset(). */
+ public static int peak() {
+ return PEAK.get();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/Recording.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/Recording.java
new file mode 100644
index 0000000..b051e55
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/Recording.java
@@ -0,0 +1,85 @@
+package com.amigoscode.batching.db;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+/** Everything the application sent to Postgres between SqlRecorder.start() and stop(). */
+public record Recording(List calls, int commits, int rollbacks) {
+
+ /** One statement and everything that was sent with it. */
+ public record Shape(String sql, int roundTrips, int rows, Map batchSizes) {
+
+ /**
+ * "40 x 50" or "39 x 50, 1 x 17": how many batches of each size, biggest first. With more than
+ * three different sizes, "2,022 of 1 to 50 rows". Empty when nothing was batched.
+ */
+ public String describeBatches() {
+ if (batchSizes.size() > 3) {
+ int batches = batchSizes.values().stream().mapToInt(Integer::intValue).sum();
+ return String.format("%,d of %,d to %,d rows", batches,
+ batchSizes.keySet().stream().min(Integer::compare).orElseThrow(),
+ batchSizes.keySet().stream().max(Integer::compare).orElseThrow());
+ }
+ List parts = new ArrayList<>();
+ batchSizes.entrySet().stream()
+ .sorted(Map.Entry.comparingByKey().reversed())
+ .forEach(size -> parts.add(String.format("%,d x %,d", size.getValue(), size.getKey())));
+ return String.join(", ", parts);
+ }
+ }
+
+ public int roundTrips() {
+ return calls.size();
+ }
+
+ public int roundTrips(String sqlPrefix) {
+ return matching(sqlPrefix).size();
+ }
+
+ /** The number of rows (sets of values) sent with statements that start with the prefix. */
+ public int rows(String sqlPrefix) {
+ return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).sum();
+ }
+
+ /** The biggest single round trip for statements that start with the prefix, in rows. */
+ public int largestBatch(String sqlPrefix) {
+ return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).max().orElse(0);
+ }
+
+ public List matching(String sqlPrefix) {
+ return calls.stream().filter(call -> call.startsWith(sqlPrefix)).toList();
+ }
+
+ /** The calls grouped by statement, in the order each statement was first sent. */
+ public List shapes() {
+ Map> grouped = new LinkedHashMap<>();
+ for (SqlCall call : calls) {
+ grouped.computeIfAbsent(call.shape(), ignored -> new ArrayList<>()).add(call);
+ }
+ List shapes = new ArrayList<>();
+ grouped.forEach((sql, sameSql) -> {
+ Map batchSizes = new TreeMap<>();
+ sameSql.stream()
+ .filter(call -> call.kind() != SqlCall.Kind.SINGLE)
+ .forEach(call -> batchSizes.merge(call.rows(), 1, Integer::sum));
+ shapes.add(new Shape(sql, sameSql.size(), sameSql.stream().mapToInt(SqlCall::rows).sum(), batchSizes));
+ });
+ return shapes;
+ }
+
+ /** A few lines for a failure message: what was sent, grouped by statement. */
+ public String describe() {
+ StringBuilder text = new StringBuilder(String.format("%,d round trips:", roundTrips()));
+ for (Shape shape : shapes()) {
+ String sql = shape.sql().length() > 90 ? shape.sql().substring(0, 90) + "..." : shape.sql();
+ text.append(String.format("%n%,d x %s", shape.roundTrips(), sql));
+ if (!shape.batchSizes().isEmpty()) {
+ text.append(" [batches: ").append(shape.describeBatches()).append("]");
+ }
+ }
+ return text.toString();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlCall.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlCall.java
new file mode 100644
index 0000000..592da9c
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlCall.java
@@ -0,0 +1,29 @@
+package com.amigoscode.batching.db;
+
+import java.util.Locale;
+
+/**
+ * One round trip from the application to Postgres: one execute() of one statement, one
+ * executeBatch() of a JDBC batch, or one COPY. {@code rows} is how many sets of values it carried:
+ * 1 for a plain statement, the batch size for a batch, the number of rows for a COPY.
+ */
+public record SqlCall(String sql, Kind kind, int rows) {
+
+ public enum Kind {
+ /** execute(), executeQuery() or executeUpdate(): one statement, one set of values. */
+ SINGLE,
+ /** executeBatch(): the same statement with many sets of values, sent together. */
+ BATCH,
+ /** COPY ... FROM STDIN: one statement, the rows stream after it. */
+ COPY
+ }
+
+ /** The statement in lower case, on one line. */
+ public String shape() {
+ return sql.strip().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT);
+ }
+
+ public boolean startsWith(String prefix) {
+ return shape().startsWith(prefix.toLowerCase(Locale.ROOT));
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlRecorder.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlRecorder.java
new file mode 100644
index 0000000..a68fd9c
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlRecorder.java
@@ -0,0 +1,219 @@
+package com.amigoscode.batching.db;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+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;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import javax.sql.DataSource;
+import org.postgresql.PGConnection;
+import org.postgresql.copy.CopyIn;
+import org.postgresql.copy.CopyManager;
+import org.postgresql.core.BaseConnection;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.jdbc.datasource.DelegatingDataSource;
+
+/**
+ * Records every round trip the application makes to Postgres, whoever makes it: Hibernate, Spring
+ * Data, JdbcTemplate or a COPY. ./demo and the tests use it to answer "how many times did this
+ * import talk to the database, and how many rows did each trip carry?"
+ *
+ * SqlRecorder.start();
+ * ... run the import ...
+ * Recording recording = SqlRecorder.stop();
+ *
+ * It wraps the DataSource, so it sees exactly what reaches the JDBC driver: one execute() is one
+ * round trip, one executeBatch() is one round trip however many rows were added to the batch.
+ * (Hibernate's own statement counters count a batch differently, which is why they are not used.)
+ *
+ * A teaching tool: do not ship a static, shared recorder like this in a real application.
+ */
+public final class SqlRecorder {
+
+ private static final Object LOCK = new Object();
+ private static final Set EXECUTE = Set.of("execute", "executeQuery", "executeUpdate", "executeLargeUpdate");
+ private static final Set EXECUTE_BATCH = Set.of("executeBatch", "executeLargeBatch");
+
+ private static List calls;
+ private static int commits;
+ private static int rollbacks;
+
+ public static void start() {
+ synchronized (LOCK) {
+ calls = new ArrayList<>();
+ commits = 0;
+ rollbacks = 0;
+ }
+ }
+
+ /** Stops recording and returns what was sent since start(). */
+ public static Recording stop() {
+ synchronized (LOCK) {
+ Recording recording = new Recording(calls == null ? List.of() : List.copyOf(calls), commits, rollbacks);
+ calls = null;
+ return recording;
+ }
+ }
+
+ private static void record(String sql, SqlCall.Kind kind, int rows) {
+ synchronized (LOCK) {
+ if (calls != null) {
+ calls.add(new SqlCall(sql, kind, rows));
+ }
+ }
+ }
+
+ private static void recordEnd(boolean commit) {
+ synchronized (LOCK) {
+ if (calls != null) {
+ if (commit) {
+ commits++;
+ } else {
+ rollbacks++;
+ }
+ }
+ }
+ }
+
+ /** Wraps every DataSource bean of the application. */
+ @Configuration
+ static class Wiring {
+
+ @Bean
+ static BeanPostProcessor recordSqlOfEveryDataSource() {
+ return new BeanPostProcessor() {
+ @Override
+ public Object postProcessAfterInitialization(Object bean, String beanName) {
+ return bean instanceof DataSource dataSource && !(bean instanceof RecordingDataSource)
+ ? new RecordingDataSource(dataSource) : bean;
+ }
+ };
+ }
+ }
+
+ private static final class RecordingDataSource extends DelegatingDataSource {
+
+ RecordingDataSource(DataSource target) {
+ super(target);
+ }
+
+ @Override
+ public Connection getConnection() throws SQLException {
+ return watch(super.getConnection());
+ }
+
+ @Override
+ public Connection getConnection(String username, String password) throws SQLException {
+ return watch(super.getConnection(username, password));
+ }
+
+ private static Connection watch(Connection connection) {
+ return proxy(Connection.class, (proxy, method, args) -> {
+ String name = method.getName();
+ if (name.equals("unwrap") && args[0] == PGConnection.class) {
+ return watchCopy(connection.unwrap(PGConnection.class));
+ }
+ Object result = call(connection, method, args);
+ if (name.equals("commit")) {
+ recordEnd(true);
+ } else if (name.equals("rollback") && args == null) {
+ recordEnd(false);
+ } else if (name.equals("prepareStatement") && result instanceof PreparedStatement statement) {
+ return watch(statement, (String) args[0]);
+ } else if (name.equals("createStatement") && result instanceof Statement statement) {
+ return watch(statement);
+ }
+ return result;
+ });
+ }
+
+ private static PreparedStatement watch(PreparedStatement statement, String sql) {
+ int[] batched = {0};
+ return proxy(PreparedStatement.class, (proxy, method, args) -> {
+ String name = method.getName();
+ if (name.equals("addBatch") && args == null) {
+ batched[0]++;
+ } else if (name.equals("clearBatch")) {
+ batched[0] = 0;
+ } else if (EXECUTE_BATCH.contains(name)) {
+ record(sql, SqlCall.Kind.BATCH, batched[0]);
+ batched[0] = 0;
+ } else if (EXECUTE.contains(name) && args == null) {
+ record(sql, SqlCall.Kind.SINGLE, 1);
+ }
+ return call(statement, method, args);
+ });
+ }
+
+ /** A plain Statement: the SQL is passed to execute() itself. */
+ private static Statement watch(Statement statement) {
+ List batch = new ArrayList<>();
+ return proxy(Statement.class, (proxy, method, args) -> {
+ String name = method.getName();
+ if (name.equals("addBatch") && args != null) {
+ batch.add((String) args[0]);
+ } else if (EXECUTE_BATCH.contains(name) && !batch.isEmpty()) {
+ record(batch.getFirst(), SqlCall.Kind.BATCH, batch.size());
+ batch.clear();
+ } else if (EXECUTE.contains(name) && args != null && args[0] instanceof String sql) {
+ record(sql, SqlCall.Kind.SINGLE, 1);
+ }
+ return call(statement, method, args);
+ });
+ }
+
+ /** COPY does not go through a Statement at all: it is the driver's CopyManager. */
+ private static PGConnection watchCopy(PGConnection connection) {
+ return proxy(PGConnection.class, (proxy, method, args) -> {
+ if (method.getName().equals("getCopyAPI")) {
+ return new RecordingCopyManager((BaseConnection) connection);
+ }
+ return call(connection, method, args);
+ });
+ }
+
+ private static T proxy(Class type, InvocationHandler handler) {
+ return type.cast(Proxy.newProxyInstance(SqlRecorder.class.getClassLoader(), new Class>[] {type}, handler));
+ }
+
+ private static Object call(Object target, Method method, Object[] args) throws Throwable {
+ try {
+ return method.invoke(target, args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ }
+ }
+ }
+
+ /** Records a COPY when it ends, with the number of rows Postgres says it stored. */
+ private static final class RecordingCopyManager extends CopyManager {
+
+ RecordingCopyManager(BaseConnection connection) throws SQLException {
+ super(connection);
+ }
+
+ @Override
+ public CopyIn copyIn(String sql) throws SQLException {
+ CopyIn copy = super.copyIn(sql);
+ return RecordingDataSource.proxy(CopyIn.class, (proxy, method, args) -> {
+ Object result = RecordingDataSource.call(copy, method, args);
+ if (method.getName().equals("endCopy")) {
+ record(sql, SqlCall.Kind.COPY, (int) (long) (Long) result);
+ }
+ return result;
+ });
+ }
+
+ }
+
+ private SqlRecorder() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Db.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Db.java
new file mode 100644
index 0000000..dce5c1a
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Db.java
@@ -0,0 +1,52 @@
+package com.amigoscode.batching.demo;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */
+final class Db {
+
+ static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5455/batching");
+ static final String USER = env("DB_USER", "batching");
+ static final String PASSWORD = env("DB_PASSWORD", "batching");
+
+ private Db() {
+ }
+
+ /**
+ * A connection for the tools themselves. pg_stat_statements is told to ignore it, so the queries
+ * ./demo and ./inspect run to count things do not show up next to the application's statements.
+ */
+ static Connection connect() throws SQLException {
+ Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("set pg_stat_statements.track = 'none'");
+ } catch (SQLException notLoadedOrNotAllowed) {
+ // Without pg_stat_statements there is nothing to hide from.
+ }
+ return connection;
+ }
+
+ /** Returns false, after printing what to do, when Postgres is not reachable. */
+ static boolean isUp() {
+ try (Connection ignored = connect()) {
+ return true;
+ } catch (SQLException e) {
+ System.out.println();
+ System.out.println("Cannot reach Postgres at " + URL);
+ System.out.println("Start it first, from this folder:");
+ System.out.println();
+ System.out.println(" docker compose up -d");
+ System.out.println();
+ System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")");
+ return false;
+ }
+ }
+
+ private static String env(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isBlank() ? fallback : value;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Demo.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Demo.java
new file mode 100644
index 0000000..edd5b0e
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Demo.java
@@ -0,0 +1,441 @@
+package com.amigoscode.batching.demo;
+
+import com.amigoscode.batching.BatchingApplication;
+import com.amigoscode.batching.db.ManagedEntities;
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.db.SqlCall;
+import com.amigoscode.batching.db.SqlRecorder;
+import com.amigoscode.batching.price.PriceChange;
+import com.amigoscode.batching.product.Product;
+import com.amigoscode.batching.product.StockLevel;
+import jakarta.persistence.EntityManagerFactory;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import javax.sql.DataSource;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.generator.Generator;
+import org.hibernate.id.IdentityGenerator;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.postgresql.core.BaseConnection;
+import org.springframework.boot.Banner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.core.env.MapPropertySource;
+
+/**
+ * Starts the real application, sends it a generated CSV feed over HTTP, and prints how many round
+ * trips the import made to Postgres, what Postgres executed, and how many entities Hibernate held in
+ * memory. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags.
+ */
+public final class Demo {
+
+ private static final List STRATEGIES = List.of("one-by-one", "batched", "rewrite", "jdbc", "copy");
+ private static final int WIDTH = 74;
+
+ private record Options(String strategy, int rows, boolean stock, boolean prices, Boolean rewrite, boolean sql) {
+
+ /** The strategy the application knows: "rewrite" is "batched" with the driver setting on. */
+ String appStrategy() {
+ return strategy.equals("rewrite") ? "batched" : strategy;
+ }
+
+ boolean jpa() {
+ return prices || !(strategy.equals("jdbc") || strategy.equals("copy"));
+ }
+ }
+
+ /** One HTTP request and everything it caused. */
+ private record Phase(String title, int status, String body, Recording recording,
+ List executed, int peakEntities, long millis) {
+
+ int rowsWritten() {
+ return recording.calls().stream()
+ .filter(call -> call.startsWith("insert") || call.startsWith("update") || call.startsWith("copy"))
+ .mapToInt(SqlCall::rows)
+ .sum();
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options;
+ try {
+ options = parse(args);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ System.out.println();
+ printHelp();
+ return;
+ }
+ if (options == null) {
+ printHelp();
+ return;
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+
+ List springArgs = new ArrayList<>(List.of(
+ "--server.port=0",
+ "--logging.level.root=WARN",
+ "--logging.level.org.apache.catalina.core.ContainerBase=OFF",
+ "--spring.web.error.include-message=always"));
+ Boolean rewrite = options.strategy().equals("rewrite") ? Boolean.TRUE : options.rewrite();
+
+ SpringApplication app = new SpringApplication(BatchingApplication.class);
+ app.setBannerMode(Banner.Mode.OFF);
+ app.setLogStartupInfo(false);
+ if (rewrite != null) {
+ // An option on the URL beats a driver property, so the override goes on the URL itself.
+ app.addInitializers(context -> {
+ var environment = context.getEnvironment();
+ String url = withRewrite(environment.getProperty("spring.datasource.url", Db.URL), rewrite);
+ environment.getPropertySources().addFirst(new MapPropertySource("demo-rewrite",
+ java.util.Map.of("spring.datasource.url", url)));
+ });
+ }
+ try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new))) {
+ run(options, context);
+ }
+ }
+
+ private static void run(Options options, ConfigurableApplicationContext context) throws Exception {
+ String baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port");
+ HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+ int batchSize = context.getEnvironment().getProperty("spring.jpa.properties.hibernate.jdbc.batch_size", Integer.class, 0);
+
+ // A throwaway request first, so the import is not slowed down by start-up work.
+ http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding());
+
+ printHeader(options, context, batchSize);
+
+ List phases = new ArrayList<>();
+ try (Connection server = Db.connect()) {
+ boolean serverStats = ServerStats.available(server);
+ if (options.prices()) {
+ phases.add(send(http, server, serverStats, "PRICE HISTORY: " + number(options.rows()) + " price changes, saveAll()",
+ "POST", baseUrl + "/api/imports/prices", Feed.products(options.rows(), false)));
+ } else {
+ phases.add(send(http, server, serverStats, "IMPORT: " + number(options.rows()) + " new products"
+ + (options.stock() ? ", each with 3 stock levels" : ""),
+ "POST", baseUrl + "/api/imports/products?strategy=" + options.appStrategy(),
+ Feed.products(options.rows(), options.stock())));
+ if (options.stock() && phases.getFirst().status() == 200) {
+ phases.add(send(http, server, serverStats, "UPDATE: the next day's feed, a new price and new stock for every product",
+ "PUT", baseUrl + "/api/imports/products", Feed.nextDay(options.rows())));
+ }
+ }
+ if (!serverStats) {
+ System.out.println("(pg_stat_statements is not loaded in this Postgres, so the server side is not shown.");
+ System.out.println(" The compose.yaml of this project loads it: docker compose down, then docker compose up -d.)");
+ System.out.println();
+ }
+ }
+
+ for (Phase phase : phases) {
+ print(phase, options.sql());
+ }
+
+ long products;
+ long stockLevels;
+ long priceChanges;
+ try (Connection connection = Db.connect()) {
+ products = count(connection, "product");
+ stockLevels = count(connection, "stock_level");
+ priceChanges = count(connection, "price_change");
+ }
+ System.out.println("Rows in the database: " + number(products) + " products, " + number(stockLevels)
+ + " stock levels, " + number(priceChanges) + " price changes");
+ System.out.println();
+
+ printResults(options, phases, batchSize, options.prices() ? priceChanges : products);
+ }
+
+ private static long count(Connection connection, String table) throws java.sql.SQLException {
+ try (var statement = connection.createStatement(); var result = statement.executeQuery("select count(*) from " + table)) {
+ result.next();
+ return result.getLong(1);
+ }
+ }
+
+ private static Phase send(HttpClient http, Connection server, boolean serverStats, String title,
+ String method, String url, String csv) throws Exception {
+ HttpRequest request = HttpRequest.newBuilder(URI.create(url))
+ .header("Content-Type", "text/csv")
+ .method(method, HttpRequest.BodyPublishers.ofString(csv))
+ .build();
+ if (serverStats) {
+ ServerStats.reset(server);
+ }
+ ManagedEntities.reset();
+ SqlRecorder.start();
+ long started = System.nanoTime();
+ HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString());
+ long millis = (System.nanoTime() - started) / 1_000_000;
+ Recording recording = SqlRecorder.stop();
+ List executed = serverStats ? ServerStats.read(server) : List.of();
+ return new Phase(title, response.statusCode(), response.body(), recording, executed, ManagedEntities.peak(), millis);
+ }
+
+ /** The URL with reWriteBatchedInserts set to the given value, whatever it said before. */
+ private static String withRewrite(String url, boolean on) {
+ String clean = url.replaceAll("(?i)([?&])reWriteBatchedInserts=[^&]*&?", "$1").replaceAll("[?&]$", "");
+ return clean + (clean.contains("?") ? "&" : "?") + "reWriteBatchedInserts=" + on;
+ }
+
+ private static void printHeader(Options options, ConfigurableApplicationContext context, int batchSize) {
+ // Ask the driver itself: the option can come from the URL or from a driver property.
+ String rewrite = "?";
+ try (Connection connection = context.getBean(DataSource.class).getConnection()) {
+ rewrite = String.valueOf(connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled());
+ } catch (Exception ignored) {
+ // Not the Postgres driver: leave it as "?".
+ }
+ var environment = context.getEnvironment();
+ System.out.println();
+ System.out.println("Strategy: " + options.strategy() + (options.prices() ? " (ignored: --prices always uses saveAll)" : "")
+ + " | rows: " + number(options.rows()));
+ System.out.println("Settings: hibernate.jdbc.batch_size=" + (batchSize == 0 ? "(not set)" : batchSize)
+ + " | order_inserts=" + environment.getProperty("spring.jpa.properties.hibernate.order_inserts", "false")
+ + " | order_updates=" + environment.getProperty("spring.jpa.properties.hibernate.order_updates", "false")
+ + " | reWriteBatchedInserts=" + rewrite);
+ SessionFactoryImplementor hibernate = context.getBean(EntityManagerFactory.class).unwrap(SessionFactoryImplementor.class);
+ if (options.prices()) {
+ System.out.println("PriceChange ids: " + describe(generator(hibernate, PriceChange.class)));
+ } else if (options.jpa()) {
+ System.out.println("Product ids: " + describe(generator(hibernate, Product.class)));
+ if (options.stock()) {
+ System.out.println("StockLevel ids: " + describe(generator(hibernate, StockLevel.class)));
+ }
+ } else {
+ System.out.println("Product ids: the column default, nextval('product_seq') or the identity. No entities.");
+ }
+ System.out.println();
+ }
+
+ private static Generator generator(SessionFactoryImplementor hibernate, Class> entity) {
+ return hibernate.getMappingMetamodel().getEntityDescriptor(entity).getGenerator();
+ }
+
+ private static String describe(Generator generator) {
+ if (generator == null) {
+ return "assigned in Java: Hibernate generates nothing";
+ }
+ if (generator instanceof IdentityGenerator) {
+ return "IDENTITY. Postgres makes each id while it runs the INSERT";
+ }
+ if (generator instanceof SequenceStyleGenerator sequence) {
+ int allocation = sequence.getOptimizer().getIncrementSize();
+ return "SEQUENCE " + sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText()
+ + ", allocationSize " + allocation + " (" + sequence.getOptimizer().getClass().getSimpleName()
+ + ": " + (allocation == 1 ? "one nextval per row" : "one nextval per " + allocation + " ids") + ")";
+ }
+ String name = generator.getClass().getSimpleName();
+ if (name.equals("UuidGenerator")) {
+ return "UuidGenerator. Hibernate makes a UUID in memory when the entity is persisted";
+ }
+ return name.equals("Assigned") ? "assigned in Java: Hibernate generates nothing" : name;
+ }
+
+ private static void print(Phase phase, boolean sql) {
+ System.out.println(phase.title());
+ System.out.println("=".repeat(Math.min(phase.title().length(), WIDTH + 20)));
+ if (phase.status() != 200) {
+ System.out.println();
+ System.out.println(" HTTP " + phase.status() + ": " + phase.body());
+ System.out.println();
+ return;
+ }
+ Recording recording = phase.recording();
+ System.out.println();
+ System.out.println("What the application sent, counted at the JDBC driver (one execute or executeBatch = one round trip)");
+ List rows = new ArrayList<>();
+ rows.add(new String[] {"round trips", "rows", "batches (count x size)", "statement"});
+ for (Recording.Shape shape : recording.shapes()) {
+ rows.add(new String[] {number(shape.roundTrips()), number(shape.rows()), shape.describeBatches(), clip(shape.sql())});
+ }
+ Table.print(rows, 0, 1);
+ if (sql) {
+ System.out.println();
+ System.out.println("The first 25 round trips, in the order they were sent");
+ List calls = recording.calls();
+ for (int i = 0; i < Math.min(25, calls.size()); i++) {
+ SqlCall call = calls.get(i);
+ System.out.printf(" %4d %-6s %4d row%s %s%n", i + 1, call.kind().name().toLowerCase(Locale.ROOT),
+ call.rows(), call.rows() == 1 ? " " : "s", clip(call.shape()));
+ }
+ }
+ if (!phase.executed().isEmpty()) {
+ System.out.println();
+ System.out.println("What Postgres executed, counted by the server (pg_stat_statements)");
+ List executed = new ArrayList<>();
+ executed.add(new String[] {"executions", "rows", "rows each", "statement"});
+ for (ServerStats.Executed statement : phase.executed()) {
+ long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls();
+ executed.add(new String[] {number(statement.calls()), number(statement.rows()), number(each),
+ clip(ServerStats.shorten(statement.query()))});
+ }
+ Table.print(executed, 0, 1, 2);
+ }
+ System.out.println();
+ System.out.println("Round trips: " + number(recording.roundTrips()));
+ System.out.println("Commits: " + number(recording.commits()));
+ System.out.println("Peak entities held: " + number(phase.peakEntities())
+ + " (the most entities in Hibernate's persistence context at one flush)");
+ System.out.println("Time taken: " + number(phase.millis()) + " ms");
+ System.out.println();
+ }
+
+ private static void printResults(Options options, List phases, int batchSize, long rowsStored) {
+ List problems = new ArrayList<>();
+ for (Phase phase : phases) {
+ if (phase.status() != 200) {
+ problems.add("FAILED. " + phase.title().split(":")[0] + " returned HTTP " + phase.status() + ".");
+ continue;
+ }
+ Recording recording = phase.recording();
+ String what = phase.title().split(":")[0].toLowerCase(Locale.ROOT);
+ int selects = recording.roundTrips("select") - recording.roundTrips("select nextval");
+ if (options.prices() && selects > 0) {
+ problems.add(number(selects) + " SELECTS. saveAll() looked up every price change before inserting it.");
+ }
+ if (recording.commits() > 1) {
+ problems.add(number(recording.commits()) + " COMMITS. Every row was its own transaction.");
+ }
+ int rowsWritten = phase.rowsWritten();
+ if (recording.roundTrips() * 10L > rowsWritten) {
+ problems.add(number(recording.roundTrips()) + " ROUND TRIPS. The " + what + " wrote " + number(rowsWritten)
+ + " rows, " + perTrip(rowsWritten, recording.roundTrips()) + " per round trip.");
+ }
+ boolean importPhase = phase == phases.getFirst() && !options.prices() && options.jpa();
+ if (importPhase && batchSize > 0 && phase.peakEntities() > 4 * batchSize) {
+ problems.add(number(phase.peakEntities()) + " ENTITIES IN MEMORY. The persistence context held the whole "
+ + what + " until it ended.");
+ }
+ }
+ if (problems.isEmpty()) {
+ Phase first = phases.getFirst();
+ StringBuilder ok = new StringBuilder("RESULT: OK. " + number(rowsStored) + " rows in "
+ + roundTrips(first.recording().roundTrips()));
+ if (phases.size() > 1) {
+ ok.append(", updated in ").append(roundTrips(phases.get(1).recording().roundTrips()));
+ }
+ if (!options.prices() && options.jpa()) {
+ ok.append(", at most ").append(number(first.peakEntities())).append(" entities in memory");
+ }
+ System.out.println(ok.append('.'));
+ } else {
+ problems.forEach(problem -> System.out.println("RESULT: " + problem));
+ }
+ System.out.println();
+ }
+
+ private static String roundTrips(int count) {
+ return number(count) + (count == 1 ? " round trip" : " round trips");
+ }
+
+ private static String perTrip(int rows, int roundTrips) {
+ double average = roundTrips == 0 ? 0 : (double) rows / roundTrips;
+ return String.format(Locale.US, "%.1f", average);
+ }
+
+ private static String clip(String sql) {
+ return sql.length() > WIDTH ? sql.substring(0, WIDTH - 3) + "..." : sql;
+ }
+
+ static String number(long value) {
+ return String.format(Locale.US, "%,d", value);
+ }
+
+ private static Options parse(String[] args) {
+ String strategy = "batched";
+ int rows = 10_000;
+ boolean stock = false;
+ boolean prices = false;
+ Boolean rewrite = null;
+ boolean sql = false;
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ switch (arg) {
+ case "--help", "-h" -> {
+ return null;
+ }
+ case "--strategy" -> {
+ strategy = value(args, ++i, arg).toLowerCase(Locale.ROOT);
+ if (!STRATEGIES.contains(strategy)) {
+ throw new IllegalArgumentException("Unknown strategy '" + strategy + "'. Use one of: " + String.join(", ", STRATEGIES));
+ }
+ }
+ case "--rows" -> rows = number(value(args, ++i, arg), arg, 1, 100_000);
+ case "--stock" -> stock = true;
+ case "--prices" -> prices = true;
+ case "--rewrite" -> {
+ String value = value(args, ++i, arg).toLowerCase(Locale.ROOT);
+ if (!value.equals("on") && !value.equals("off")) {
+ throw new IllegalArgumentException("--rewrite must be on or off, got: " + value);
+ }
+ rewrite = value.equals("on");
+ }
+ case "--sql" -> sql = true;
+ default -> throw new IllegalArgumentException("Unknown option: " + arg);
+ }
+ }
+ if (stock && prices) {
+ throw new IllegalArgumentException("Use --stock or --prices, not both.");
+ }
+ if (stock && (strategy.equals("jdbc") || strategy.equals("copy"))) {
+ throw new IllegalArgumentException("--stock needs JPA: the " + strategy + " importer does not write stock levels (that is one of its trade-offs).");
+ }
+ return new Options(strategy, rows, stock, prices, rewrite, sql);
+ }
+
+ private static String value(String[] args, int index, String option) {
+ if (index >= args.length) {
+ throw new IllegalArgumentException(option + " needs a value");
+ }
+ return args[index];
+ }
+
+ private static int number(String value, String option, int min, int max) {
+ try {
+ int number = Integer.parseInt(value.replace(",", "").replace("_", ""));
+ if (number < min || number > max) {
+ throw new NumberFormatException();
+ }
+ return number;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(option + " must be a number from " + min + " to " + number(max) + ", got: " + value);
+ }
+ }
+
+ private static void printHelp() {
+ System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])");
+ System.out.println();
+ System.out.println(" --rows how many products the feed has (default: 10000)");
+ System.out.println(" --strategy how they reach the database (default: batched)");
+ System.out.println(" one-by-one JPA, one transaction per row (never changes: the reference)");
+ System.out.println(" batched JPA, one transaction, saveAll (Tasks 2 to 6 change this)");
+ System.out.println(" rewrite batched, with reWriteBatchedInserts=true for this run");
+ System.out.println(" jdbc JdbcTemplate.batchUpdate, no entities (Task 8)");
+ System.out.println(" copy Postgres COPY through the driver's CopyManager (Task 8)");
+ System.out.println(" --rewrite on|off force reWriteBatchedInserts for this run (default: application.properties)");
+ System.out.println(" --stock every product gets 3 stock levels, then a second feed updates them all");
+ System.out.println(" --prices write the price history instead: ids are UUIDs made in Java");
+ System.out.println(" --sql also list the first 25 round trips, in order");
+ System.out.println();
+ System.out.println("Examples:");
+ System.out.println(" ./demo");
+ System.out.println(" ./demo --strategy rewrite");
+ System.out.println(" ./demo --stock --rows 2000");
+ System.out.println(" ./demo --prices --rows 1000");
+ System.out.println(" ./demo --strategy copy --rows 100000");
+ }
+
+ private Demo() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Feed.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Feed.java
new file mode 100644
index 0000000..461ff10
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Feed.java
@@ -0,0 +1,55 @@
+package com.amigoscode.batching.demo;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+/** Builds the supplier's CSV feed. Same input every time, so two runs can be compared. */
+final class Feed {
+
+ static final List WAREHOUSES = List.of("GLA", "LON", "MAN");
+
+ private static final String[] COLOURS = {"Black", "White", "Red", "Blue", "Green", "Grey", "Yellow", "Navy"};
+ private static final String[] THINGS = {"mug", "kettle", "lamp", "chair", "desk", "pillow", "towel", "teapot", "vase", "clock"};
+
+ private Feed() {
+ }
+
+ /** The first feed: new products, optionally with stock in three warehouses. */
+ static String products(int rows, boolean withStock) {
+ return build(rows, withStock, 0);
+ }
+
+ /** The next day's feed: the same SKUs, every price up by 10% and different stock. */
+ static String nextDay(int rows) {
+ return build(rows, true, 1);
+ }
+
+ private static String build(int rows, boolean withStock, int day) {
+ StringBuilder csv = new StringBuilder(rows * 48);
+ csv.append("sku,name,price");
+ if (withStock) {
+ WAREHOUSES.forEach(warehouse -> csv.append(',').append(warehouse));
+ }
+ csv.append('\n');
+ for (int i = 1; i <= rows; i++) {
+ BigDecimal price = BigDecimal.valueOf(100 + (i * 37L) % 9900, 2);
+ if (day > 0) {
+ price = price.multiply(new BigDecimal("1.10")).setScale(2, java.math.RoundingMode.HALF_UP);
+ }
+ csv.append(sku(i)).append(',')
+ .append(COLOURS[i % COLOURS.length]).append(' ').append(THINGS[i % THINGS.length]).append(" no. ").append(i)
+ .append(',').append(price.toPlainString());
+ if (withStock) {
+ for (int w = 0; w < WAREHOUSES.size(); w++) {
+ csv.append(',').append((i * (w + 3) + day * 5) % 40);
+ }
+ }
+ csv.append('\n');
+ }
+ return csv.toString();
+ }
+
+ static String sku(int i) {
+ return String.format("SKU-%06d", i);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Inspect.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Inspect.java
new file mode 100644
index 0000000..69cd8fa
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Inspect.java
@@ -0,0 +1,149 @@
+package com.amigoscode.batching.demo;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Shows what the database holds after a ./demo run: how each table gets its ids, the sequences and
+ * how far they have moved, how far apart the stored ids are, and every statement Postgres executed
+ * for the last request of the demo (pg_stat_statements). Run it with ./inspect (or .\inspect on
+ * Windows) after ./demo.
+ */
+public final class Inspect {
+
+ private static final String ID_COLUMNS = """
+ select c.table_name as "table",
+ c.data_type as "type",
+ case when c.is_identity = 'YES' then 'IDENTITY: Postgres makes it while it runs the INSERT'
+ when c.column_default like 'nextval%' then 'DEFAULT ' || c.column_default
+ else 'none: the application must send it' end as "where the id comes from"
+ from information_schema.columns c
+ where c.table_schema = current_schema()
+ and c.table_name in ('product', 'stock_level', 'price_change')
+ and c.column_name = 'id'
+ order by c.table_name
+ """;
+
+ private static final String SEQUENCES = """
+ select sequencename as "sequence",
+ increment_by as "increment by",
+ coalesce(last_value::text, '(never used)') as "last value handed out"
+ from pg_sequences
+ where schemaname = current_schema()
+ order by sequencename
+ """;
+
+ private static final String IDS = """
+ with ids as (
+ select 'product' as t, null::text as uuid, id as n from product
+ union all select 'stock_level', null, id from stock_level
+ union all select 'price_change', id::text, null from price_change
+ ),
+ steps as (
+ select t, n - lag(n) over (partition by t order by n) as step from ids where n is not null
+ ),
+ common as (
+ select t, step, count(*) as times,
+ row_number() over (partition by t order by count(*) desc, step) as rank
+ from steps where step is not null group by t, step
+ )
+ select tables.t as "table",
+ to_char(count(i.t), 'FM999,999,990') as "rows",
+ coalesce(min(i.n)::text, min(i.uuid), '') as "lowest id",
+ coalesce(max(i.n)::text, max(i.uuid), '') as "highest id",
+ coalesce((select string_agg('+' || c.step || ' (' || to_char(c.times, 'FM999,999,990') || 'x)', ', ' order by c.rank)
+ from common c where c.t = tables.t and c.rank <= 3), '') as "most common gaps between neighbouring ids"
+ from (values ('product'), ('stock_level'), ('price_change')) as tables (t)
+ left join ids i on i.t = tables.t
+ group by tables.t
+ order by tables.t
+ """;
+
+ public static void main(String[] args) throws Exception {
+ if (args.length > 0) {
+ System.out.println("Usage: ./inspect (Windows: .\\inspect)");
+ System.out.println();
+ System.out.println("Run it after ./demo. It reads the database only, and changes nothing.");
+ return;
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+ try (Connection connection = Db.connect()) {
+ if (!tablesExist(connection)) {
+ System.out.println();
+ System.out.println("The tables do not exist yet. Run ./demo first.");
+ System.out.println();
+ return;
+ }
+ System.out.println();
+ System.out.println("WHERE EACH TABLE GETS ITS IDS (information_schema.columns)");
+ printTable(connection, ID_COLUMNS);
+ System.out.println();
+ System.out.println("SEQUENCES (pg_sequences)");
+ if (printTable(connection, SEQUENCES) == 0) {
+ System.out.println(" none.");
+ }
+ System.out.println();
+ System.out.println("THE ROWS AND THEIR IDS");
+ printTable(connection, IDS);
+ System.out.println();
+ System.out.println("WHAT POSTGRES EXECUTED FOR THE LAST REQUEST OF ./demo (pg_stat_statements)");
+ if (!ServerStats.available(connection)) {
+ System.out.println(" pg_stat_statements is not loaded in this Postgres. The compose.yaml of this project loads it:");
+ System.out.println(" docker compose down, then docker compose up -d.");
+ } else {
+ List rows = new ArrayList<>();
+ rows.add(new String[] {"executions", "rows", "rows each", "statement"});
+ for (ServerStats.Executed statement : ServerStats.read(connection)) {
+ long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls();
+ String query = ServerStats.shorten(statement.query());
+ rows.add(new String[] {Demo.number(statement.calls()), Demo.number(statement.rows()), Demo.number(each),
+ query.length() > 90 ? query.substring(0, 87) + "..." : query});
+ }
+ Table.print(rows, 0, 1, 2);
+ }
+ System.out.println();
+ }
+ }
+
+ private static boolean tablesExist(Connection connection) throws SQLException {
+ try (Statement statement = connection.createStatement();
+ ResultSet result = statement.executeQuery("select to_regclass('product') is not null")) {
+ result.next();
+ return result.getBoolean(1);
+ }
+ }
+
+ /** Prints a query result as a plain text table and returns the number of rows. */
+ private static int printTable(Connection connection, String sql) throws SQLException {
+ List rows = new ArrayList<>();
+ try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) {
+ int columns = result.getMetaData().getColumnCount();
+ String[] header = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ header[c] = result.getMetaData().getColumnLabel(c + 1);
+ }
+ rows.add(header);
+ while (result.next()) {
+ String[] row = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ String value = result.getString(c + 1);
+ row[c] = value == null ? "" : value;
+ }
+ rows.add(row);
+ }
+ }
+ if (rows.size() > 1) {
+ Table.print(rows);
+ }
+ return rows.size() - 1;
+ }
+
+ private Inspect() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/ServerStats.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/ServerStats.java
new file mode 100644
index 0000000..e5ed34b
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/ServerStats.java
@@ -0,0 +1,72 @@
+package com.amigoscode.batching.demo;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Reads pg_stat_statements: what Postgres itself executed, counted on the server. The application
+ * side (SqlRecorder) counts round trips; this side counts statements. They are not the same number
+ * once the driver starts rewriting batches.
+ */
+final class ServerStats {
+
+ /** One statement as Postgres normalised it ($1, $2 for the values), how often it ran, and the rows. */
+ record Executed(String query, long calls, long rows) {
+ }
+
+ private static final String READ = """
+ select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows
+ from pg_stat_statements
+ where dbid = (select oid from pg_database where datname = current_database())
+ and query !~* 'pg_stat_statements|pg_catalog|information_schema|pg_sequences|pg_class|pg_attribute'
+ and query ~* '^\\s*(insert|update|delete|select|copy|with)'
+ order by calls desc, query
+ """;
+
+ private ServerStats() {
+ }
+
+ /** False when the extension is not loaded (compose.yaml loads it; another Postgres may not). */
+ static boolean available(Connection connection) {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("select 1 from pg_stat_statements limit 1");
+ return true;
+ } catch (SQLException e) {
+ return false;
+ }
+ }
+
+ static void reset(Connection connection) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("select pg_stat_statements_reset()");
+ }
+ }
+
+ static List read(Connection connection) throws SQLException {
+ List executed = new ArrayList<>();
+ try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(READ)) {
+ while (result.next()) {
+ executed.add(new Executed(result.getString(1), result.getLong(2), result.getLong(3)));
+ }
+ }
+ return executed;
+ }
+
+ /** A multi-row INSERT has one "($1,$2,$3)" per row: keeps the first one and replaces the rest with "...". */
+ static String shorten(String query) {
+ int values = query.toLowerCase().indexOf(" values (");
+ if (values < 0) {
+ return query;
+ }
+ int firstEnd = query.indexOf(')', values);
+ int rest = query.indexOf("),(", values);
+ if (rest < 0) {
+ rest = query.indexOf("), (", values);
+ }
+ return rest < 0 || rest != firstEnd ? query : query.substring(0, firstEnd + 1) + ",...";
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Table.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Table.java
new file mode 100644
index 0000000..15e2cda
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Table.java
@@ -0,0 +1,41 @@
+package com.amigoscode.batching.demo;
+
+import java.util.Arrays;
+import java.util.List;
+
+/** Prints rows as a plain text table. The first row is the header. */
+final class Table {
+
+ private Table() {
+ }
+
+ /** {@code rightAligned} are the column numbers to align to the right (the numbers). */
+ static void print(List rows, int... rightAligned) {
+ if (rows.size() == 1) {
+ System.out.println(" (nothing)");
+ return;
+ }
+ int[] widths = new int[rows.getFirst().length];
+ for (String[] row : rows) {
+ for (int c = 0; c < row.length; c++) {
+ widths[c] = Math.max(widths[c], row[c].length());
+ }
+ }
+ for (int r = 0; r < rows.size(); r++) {
+ StringBuilder line = new StringBuilder(" ");
+ for (int c = 0; c < widths.length; c++) {
+ int column = c;
+ boolean right = r > 0 && Arrays.stream(rightAligned).anyMatch(n -> n == column);
+ line.append(String.format("%" + (right ? "" : "-") + widths[c] + "s", rows.get(r)[c])).append(" ");
+ }
+ System.out.println(line.toString().stripTrailing());
+ if (r == 0) {
+ StringBuilder rule = new StringBuilder(" ");
+ for (int width : widths) {
+ rule.append("-".repeat(width)).append(" ");
+ }
+ System.out.println(rule.toString().stripTrailing());
+ }
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/BadCsvException.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/BadCsvException.java
new file mode 100644
index 0000000..c75efc6
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/BadCsvException.java
@@ -0,0 +1,16 @@
+package com.amigoscode.batching.imports;
+
+/** A line of the uploaded CSV that cannot be read. Becomes a 400 with the line number. */
+public class BadCsvException extends RuntimeException {
+
+ private final int line;
+
+ public BadCsvException(int line, String problem) {
+ super("Line " + line + ": " + problem);
+ this.line = line;
+ }
+
+ public int line() {
+ return line;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportController.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportController.java
new file mode 100644
index 0000000..c4c3599
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportController.java
@@ -0,0 +1,47 @@
+package com.amigoscode.batching.imports;
+
+import java.io.Reader;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * The supplier's feed arrives as CSV in the request body (see ProductCsv for the format).
+ *
+ *
+ * POST /api/imports/products?strategy=batched new products: one-by-one | batched | jdbc | copy
+ * PUT /api/imports/products same SKUs again: new prices and new stock
+ * POST /api/imports/prices one price change per row, into the price history
+ *
+ */
+@RestController
+@RequestMapping("/api/imports")
+public class ImportController {
+
+ public record ImportResponse(String strategy, long rows) {
+ }
+
+ private final ImportService imports;
+
+ public ImportController(ImportService imports) {
+ this.imports = imports;
+ }
+
+ @PostMapping(path = "/products", consumes = "text/csv")
+ public ImportResponse importProducts(@RequestParam(defaultValue = "batched") String strategy, Reader body) {
+ ImportStrategy chosen = ImportStrategy.from(strategy);
+ return new ImportResponse(chosen.label(), imports.importProducts(chosen, ProductCsv.read(body)));
+ }
+
+ @PutMapping(path = "/products", consumes = "text/csv")
+ public ImportResponse updateProducts(Reader body) {
+ return new ImportResponse("update", imports.updateProducts(ProductCsv.read(body).toList()));
+ }
+
+ @PostMapping(path = "/prices", consumes = "text/csv")
+ public ImportResponse recordPrices(Reader body) {
+ return new ImportResponse("price-history", imports.recordPrices(ProductCsv.read(body).toList()));
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportService.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportService.java
new file mode 100644
index 0000000..a3276d9
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportService.java
@@ -0,0 +1,40 @@
+package com.amigoscode.batching.imports;
+
+import com.amigoscode.batching.price.PriceHistory;
+import com.amigoscode.batching.product.JdbcProductImporter;
+import com.amigoscode.batching.product.ProductImporter;
+import com.amigoscode.batching.product.ProductRow;
+import java.util.List;
+import org.springframework.stereotype.Service;
+
+/** Picks the importer. Deliberately not transactional: each importer decides its own transactions. */
+@Service
+public class ImportService {
+
+ private final ProductImporter jpa;
+ private final JdbcProductImporter jdbc;
+ private final PriceHistory priceHistory;
+
+ public ImportService(ProductImporter jpa, JdbcProductImporter jdbc, PriceHistory priceHistory) {
+ this.jpa = jpa;
+ this.jdbc = jdbc;
+ this.priceHistory = priceHistory;
+ }
+
+ public long importProducts(ImportStrategy strategy, Iterable rows) {
+ return switch (strategy) {
+ case ONE_BY_ONE -> jpa.importOneByOne(rows);
+ case BATCHED -> jpa.importBatched(rows);
+ case JDBC -> jdbc.batchInsert(rows);
+ case COPY -> jdbc.copy(rows);
+ };
+ }
+
+ public long updateProducts(List rows) {
+ return jpa.updateAll(rows);
+ }
+
+ public long recordPrices(List rows) {
+ return priceHistory.record(rows);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java
new file mode 100644
index 0000000..905bca8
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java
@@ -0,0 +1,40 @@
+package com.amigoscode.batching.imports;
+
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.stream.Collectors;
+
+/** How the rows of an import reach the database. Chosen per request with ?strategy=. */
+public enum ImportStrategy {
+
+ /** JPA, one transaction per row. Stays as it is, so you can always compare against it. */
+ ONE_BY_ONE,
+ /** JPA, the whole file in one transaction with saveAll. Tasks 2 to 6. */
+ BATCHED,
+ /** JdbcTemplate.batchUpdate, no entities. Task 8. */
+ JDBC,
+ /** Postgres COPY through the driver's CopyManager. Task 8. */
+ COPY;
+
+ public String label() {
+ return name().toLowerCase(Locale.ROOT).replace('_', '-');
+ }
+
+ public static ImportStrategy from(String value) {
+ return Arrays.stream(values())
+ .filter(strategy -> strategy.label().equals(value == null ? "" : value.trim().toLowerCase(Locale.ROOT)))
+ .findFirst()
+ .orElseThrow(() -> new UnknownStrategyException(value));
+ }
+
+ public static String labels() {
+ return Arrays.stream(values()).map(ImportStrategy::label).collect(Collectors.joining(", "));
+ }
+
+ public static class UnknownStrategyException extends RuntimeException {
+
+ public UnknownStrategyException(String value) {
+ super("Unknown strategy '" + value + "'. Use one of: " + labels());
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ProductCsv.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ProductCsv.java
new file mode 100644
index 0000000..21dbd43
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ProductCsv.java
@@ -0,0 +1,184 @@
+package com.amigoscode.batching.imports;
+
+import com.amigoscode.batching.product.ProductRow;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.UncheckedIOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+/**
+ * Reads a product feed one row at a time, so a big file is never held in memory as a whole.
+ *
+ *
+ * sku,name,price,LON,MAN
+ * SKU-00001,"Mug, large",7.50,12,3
+ *
+ *
+ * The first three columns are fixed. Every column after them is a warehouse, and its value is the
+ * stock in that warehouse. Fields may be quoted with double quotes, and a quote inside a quoted
+ * field is written twice ("").
+ */
+public final class ProductCsv implements Iterable {
+
+ private final Reader reader;
+ private boolean used;
+
+ private ProductCsv(Reader reader) {
+ this.reader = reader;
+ }
+
+ public static ProductCsv read(Reader reader) {
+ return new ProductCsv(reader);
+ }
+
+ /** Can be iterated once: the rows are read from the reader as you go. */
+ @Override
+ public Iterator iterator() {
+ if (used) {
+ throw new IllegalStateException("A ProductCsv can only be read once");
+ }
+ used = true;
+ Records records = new Records(reader);
+ List header = records.next();
+ if (header == null || header.size() < 3
+ || !header.get(0).equals("sku") || !header.get(1).equals("name") || !header.get(2).equals("price")) {
+ throw new BadCsvException(1, "the first line must be the header sku,name,price followed by optional warehouse codes");
+ }
+ List warehouses = List.copyOf(header.subList(3, header.size()));
+ return new Iterator<>() {
+
+ private List next = records.next();
+
+ @Override
+ public boolean hasNext() {
+ return next != null;
+ }
+
+ @Override
+ public ProductRow next() {
+ if (next == null) {
+ throw new NoSuchElementException();
+ }
+ ProductRow row = toRow(next, records.line(), header.size(), warehouses);
+ next = records.next();
+ return row;
+ }
+ };
+ }
+
+ /** Reads the whole file into a list. Fine for a small file, or when you need every row at once. */
+ public List toList() {
+ List rows = new ArrayList<>();
+ forEach(rows::add);
+ return rows;
+ }
+
+ private static ProductRow toRow(List fields, int line, int columns, List warehouses) {
+ if (fields.size() != columns) {
+ throw new BadCsvException(line, "expected " + columns + " fields, found " + fields.size());
+ }
+ if (fields.get(0).isBlank()) {
+ throw new BadCsvException(line, "sku is empty");
+ }
+ BigDecimal price;
+ try {
+ price = new BigDecimal(fields.get(2).trim());
+ } catch (NumberFormatException e) {
+ throw new BadCsvException(line, "price is not a number: " + fields.get(2));
+ }
+ Map stock = new LinkedHashMap<>();
+ for (int i = 0; i < warehouses.size(); i++) {
+ String value = fields.get(3 + i).trim();
+ try {
+ stock.put(warehouses.get(i), Integer.parseInt(value));
+ } catch (NumberFormatException e) {
+ throw new BadCsvException(line, "stock for " + warehouses.get(i) + " is not a whole number: " + value);
+ }
+ }
+ return new ProductRow(fields.get(0).trim(), fields.get(1), price, stock);
+ }
+
+ /** Splits the text into records of fields. Knows about quotes, nothing else. */
+ private static final class Records {
+
+ private final Reader reader;
+ private int linesRead;
+ private int recordStart;
+
+ Records(Reader reader) {
+ this.reader = reader;
+ }
+
+ /** The line the last record started on. */
+ int line() {
+ return recordStart;
+ }
+
+ /** The next record, or null at the end of the file. Empty lines are skipped. */
+ List next() {
+ int c = read();
+ while (c == '\n' || c == '\r') {
+ if (c == '\n') {
+ linesRead++;
+ }
+ c = read();
+ }
+ if (c == -1) {
+ return null;
+ }
+ recordStart = linesRead + 1;
+ List fields = new ArrayList<>();
+ StringBuilder field = new StringBuilder();
+ boolean quoted = false;
+ while (true) {
+ if (quoted) {
+ if (c == -1) {
+ throw new BadCsvException(recordStart, "a quoted field is never closed");
+ }
+ if (c == '"') {
+ int after = read();
+ if (after != '"') {
+ quoted = false;
+ c = after;
+ continue;
+ }
+ field.append('"');
+ } else {
+ if (c == '\n') {
+ linesRead++;
+ }
+ field.append((char) c);
+ }
+ } else if (c == '"' && field.isEmpty()) {
+ quoted = true;
+ } else if (c == ',') {
+ fields.add(field.toString());
+ field.setLength(0);
+ } else if (c == '\n' || c == -1) {
+ if (c == '\n') {
+ linesRead++;
+ }
+ fields.add(field.toString());
+ return fields;
+ } else if (c != '\r') {
+ field.append((char) c);
+ }
+ c = read();
+ }
+ }
+
+ private int read() {
+ try {
+ return reader.read();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChange.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChange.java
new file mode 100644
index 0000000..f152c58
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChange.java
@@ -0,0 +1,80 @@
+package com.amigoscode.batching.price;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.PostLoad;
+import jakarta.persistence.PostPersist;
+import jakarta.persistence.Table;
+import jakarta.persistence.Transient;
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.UUID;
+import org.springframework.data.domain.Persistable;
+
+/**
+ * One line of the price history. The id is a UUID made in Java, so the database is not asked for
+ * one.
+ *
+ * Spring Data's save() decides between persist (INSERT) and merge (SELECT, then INSERT or
+ * UPDATE) by asking isNew(). By default "new" means "the id is null", and this id is never null.
+ * Implementing Persistable answers the question properly: new until it has been saved or loaded.
+ */
+@Entity
+@Table(name = "price_change")
+public class PriceChange implements Persistable {
+
+ @Id
+ private UUID id;
+
+ private String sku;
+
+ private BigDecimal price;
+
+ private Instant changedAt;
+
+ @Transient
+ private boolean isNew = true;
+
+ protected PriceChange() {
+ }
+
+ public PriceChange(String sku, BigDecimal price, Instant changedAt) {
+ this.id = UUID.randomUUID();
+ this.sku = sku;
+ this.price = price;
+ this.changedAt = changedAt;
+ }
+
+ @Override
+ public UUID getId() {
+ return id;
+ }
+
+ @Override
+ public boolean isNew() {
+ return isNew;
+ }
+
+ /** Once it is in the database, the next save() must be a merge (an UPDATE), not a second INSERT. */
+ @PostPersist
+ @PostLoad
+ void markNotNew() {
+ isNew = false;
+ }
+
+ public String getSku() {
+ return sku;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public void setPrice(BigDecimal price) {
+ this.price = price;
+ }
+
+ public Instant getChangedAt() {
+ return changedAt;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java
new file mode 100644
index 0000000..aa3701b
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java
@@ -0,0 +1,7 @@
+package com.amigoscode.batching.price;
+
+import java.util.UUID;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface PriceChangeRepository extends JpaRepository {
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceHistory.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceHistory.java
new file mode 100644
index 0000000..c979835
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceHistory.java
@@ -0,0 +1,28 @@
+package com.amigoscode.batching.price;
+
+import com.amigoscode.batching.product.ProductRow;
+import java.time.Instant;
+import java.util.List;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/** Writes one price change per row of the feed, all in one transaction. */
+@Service
+public class PriceHistory {
+
+ private final PriceChangeRepository priceChanges;
+
+ public PriceHistory(PriceChangeRepository priceChanges) {
+ this.priceChanges = priceChanges;
+ }
+
+ @Transactional
+ public int record(List rows) {
+ Instant now = Instant.now();
+ List changes = rows.stream()
+ .map(row -> new PriceChange(row.sku(), row.price(), now))
+ .toList();
+ priceChanges.saveAll(changes);
+ return changes.size();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java
new file mode 100644
index 0000000..fa28d92
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java
@@ -0,0 +1,96 @@
+package com.amigoscode.batching.product;
+
+import java.nio.charset.StandardCharsets;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+import org.postgresql.PGConnection;
+import org.postgresql.copy.CopyIn;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.jdbc.core.ConnectionCallback;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Imports products without JPA: no entities, no persistence context, no cascades. The id comes from
+ * the column's default (nextval of the sequence), and stock levels are not imported at all.
+ */
+@Service
+public class JdbcProductImporter {
+
+ private static final String INSERT = "insert into product (sku, name, price) values (?, ?, ?)";
+ private static final String COPY = "copy product (sku, name, price) from stdin with (format csv)";
+
+ private final JdbcTemplate jdbc;
+ private final int batchSize;
+
+ public JdbcProductImporter(JdbcTemplate jdbc,
+ @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) {
+ this.jdbc = jdbc;
+ this.batchSize = batchSize;
+ }
+
+ /** JdbcTemplate.batchUpdate: one round trip per batchSize rows, in one transaction. */
+ @Transactional
+ public int batchInsert(Iterable rows) {
+ List chunk = new ArrayList<>(batchSize);
+ int count = 0;
+ for (ProductRow row : rows) {
+ chunk.add(row);
+ count++;
+ if (chunk.size() == batchSize) {
+ insert(chunk);
+ }
+ }
+ insert(chunk);
+ return count;
+ }
+
+ private void insert(List chunk) {
+ if (chunk.isEmpty()) {
+ return;
+ }
+ jdbc.batchUpdate(INSERT, chunk, chunk.size(), (statement, row) -> {
+ statement.setString(1, row.sku());
+ statement.setString(2, row.name());
+ statement.setBigDecimal(3, row.price());
+ });
+ chunk.clear();
+ }
+
+ /**
+ * COPY: one statement, and the rows stream after it as CSV text. Every text field is quoted and
+ * every quote inside it doubled, so commas, quotes and line breaks in a name arrive unchanged.
+ */
+ @Transactional
+ public long copy(Iterable rows) {
+ return jdbc.execute((ConnectionCallback) connection -> {
+ CopyIn copy = connection.unwrap(PGConnection.class).getCopyAPI().copyIn(COPY);
+ try {
+ for (ProductRow row : rows) {
+ byte[] line = (csv(row.sku()) + "," + csv(row.name()) + "," + row.price().toPlainString() + "\n")
+ .getBytes(StandardCharsets.UTF_8);
+ copy.writeToCopy(line, 0, line.length);
+ }
+ return copy.endCopy();
+ } finally {
+ if (copy.isActive()) {
+ cancel(copy);
+ }
+ }
+ });
+ }
+
+ private static String csv(String value) {
+ return "\"" + value.replace("\"", "\"\"") + "\"";
+ }
+
+ private static void cancel(CopyIn copy) {
+ try {
+ copy.cancelCopy();
+ } catch (SQLException ignored) {
+ // The COPY already failed. That first error is the one worth reporting.
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/Product.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/Product.java
new file mode 100644
index 0000000..256310b
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/Product.java
@@ -0,0 +1,91 @@
+package com.amigoscode.batching.product;
+
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.SequenceGenerator;
+import jakarta.persistence.Table;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+@Entity
+@Table(name = "product")
+public class Product {
+
+ /**
+ * The id comes from product_seq. Hibernate asks the sequence for a value once and then hands
+ * out 50 ids from memory, so it knows every id before it sends a single INSERT, and can send the
+ * INSERTs in batches. allocationSize must be the same number as the sequence's INCREMENT BY.
+ */
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_ids")
+ @SequenceGenerator(name = "product_ids", sequenceName = "product_seq", allocationSize = 50)
+ private Long id;
+
+ private String sku;
+
+ private String name;
+
+ private BigDecimal price;
+
+ @OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
+ private List stockLevels = new ArrayList<>();
+
+ protected Product() {
+ }
+
+ public Product(String sku, String name, BigDecimal price) {
+ this.sku = sku;
+ this.name = name;
+ this.price = price;
+ }
+
+ /** A new product with one stock level per warehouse in the row. */
+ public static Product from(ProductRow row) {
+ Product product = new Product(row.sku(), row.name(), row.price());
+ new TreeMap<>(row.stock()).forEach(product::addStock);
+ return product;
+ }
+
+ public void addStock(String warehouse, int quantity) {
+ stockLevels.add(new StockLevel(this, warehouse, quantity));
+ }
+
+ /** Takes the new price and the new stock per warehouse from the feed. */
+ public void update(ProductRow row) {
+ this.price = row.price();
+ Map stock = row.stock();
+ for (StockLevel level : stockLevels) {
+ Integer quantity = stock.get(level.getWarehouse());
+ if (quantity != null) {
+ level.setQuantity(quantity);
+ }
+ }
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getSku() {
+ return sku;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public List getStockLevels() {
+ return stockLevels;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductImporter.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductImporter.java
new file mode 100644
index 0000000..7f62764
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductImporter.java
@@ -0,0 +1,88 @@
+package com.amigoscode.batching.product;
+
+import jakarta.persistence.EntityManager;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/** Imports the supplier's feed with JPA. */
+@Service
+public class ProductImporter {
+
+ /** Postgres accepts at most 32,767 bind parameters in one statement, so a long IN list is split. */
+ private static final int SKUS_PER_QUERY = 1_000;
+
+ private final ProductRepository products;
+ private final EntityManager entityManager;
+ private final int batchSize;
+
+ public ProductImporter(ProductRepository products, EntityManager entityManager,
+ @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) {
+ this.products = products;
+ this.entityManager = entityManager;
+ this.batchSize = batchSize;
+ }
+
+ /**
+ * The reference. Not @Transactional, so every save() is its own transaction: one INSERT and one
+ * COMMIT per row. Leave this one as it is, so you can always compare against it.
+ */
+ public int importOneByOne(Iterable rows) {
+ int count = 0;
+ for (ProductRow row : rows) {
+ products.save(Product.from(row));
+ count++;
+ }
+ return count;
+ }
+
+ /**
+ * The whole file in one transaction. Every batchSize products the persistence context is flushed
+ * (the INSERTs are sent, as one JDBC batch) and cleared (Hibernate forgets those entities), so
+ * memory stays flat however big the file is. Still one transaction: flush is not commit.
+ */
+ @Transactional
+ public int importBatched(Iterable rows) {
+ List chunk = new ArrayList<>(batchSize);
+ int count = 0;
+ for (ProductRow row : rows) {
+ chunk.add(Product.from(row));
+ count++;
+ if (chunk.size() == batchSize) {
+ saveAndForget(chunk);
+ }
+ }
+ saveAndForget(chunk);
+ return count;
+ }
+
+ private void saveAndForget(List chunk) {
+ products.saveAll(chunk);
+ entityManager.flush();
+ entityManager.clear();
+ chunk.clear();
+ }
+
+ /** The next day's feed: same SKUs, new prices and new stock. Returns how many products changed. */
+ @Transactional
+ public int updateAll(List rows) {
+ Map bySku = new LinkedHashMap<>();
+ rows.forEach(row -> bySku.put(row.sku(), row));
+ List skus = new ArrayList<>(bySku.keySet());
+ int updated = 0;
+ for (int from = 0; from < skus.size(); from += SKUS_PER_QUERY) {
+ List page = skus.subList(from, Math.min(from + SKUS_PER_QUERY, skus.size()));
+ for (Product product : products.findWithStockLevelsBySkuIn(page)) {
+ product.update(bySku.get(product.getSku()));
+ updated++;
+ }
+ }
+ // No save() needed: every product is managed, so Hibernate sends an UPDATE for each one it
+ // finds changed when the transaction commits.
+ return updated;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRepository.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRepository.java
new file mode 100644
index 0000000..abb1615
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRepository.java
@@ -0,0 +1,13 @@
+package com.amigoscode.batching.product;
+
+import java.util.Collection;
+import java.util.List;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+public interface ProductRepository extends JpaRepository {
+
+ @Query("select distinct p from Product p left join fetch p.stockLevels where p.sku in :skus")
+ List findWithStockLevelsBySkuIn(@Param("skus") Collection skus);
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRow.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRow.java
new file mode 100644
index 0000000..b936374
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRow.java
@@ -0,0 +1,16 @@
+package com.amigoscode.batching.product;
+
+import java.math.BigDecimal;
+import java.util.Map;
+
+/** One line of the supplier's feed. {@code stock} is the quantity per warehouse code, and may be empty. */
+public record ProductRow(String sku, String name, BigDecimal price, Map stock) {
+
+ public ProductRow {
+ stock = Map.copyOf(stock);
+ }
+
+ public ProductRow(String sku, String name, BigDecimal price) {
+ this(sku, name, price, Map.of());
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/StockLevel.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/StockLevel.java
new file mode 100644
index 0000000..95579ea
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/StockLevel.java
@@ -0,0 +1,55 @@
+package com.amigoscode.batching.product;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.SequenceGenerator;
+import jakarta.persistence.Table;
+
+/** How many of a product one warehouse holds. Saved together with its product (cascade). */
+@Entity
+@Table(name = "stock_level")
+public class StockLevel {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "stock_level_ids")
+ @SequenceGenerator(name = "stock_level_ids", sequenceName = "stock_level_seq", allocationSize = 50)
+ private Long id;
+
+ @ManyToOne(fetch = FetchType.LAZY, optional = false)
+ @JoinColumn(name = "product_id")
+ private Product product;
+
+ private String warehouse;
+
+ private int quantity;
+
+ protected StockLevel() {
+ }
+
+ StockLevel(Product product, String warehouse, int quantity) {
+ this.product = product;
+ this.warehouse = warehouse;
+ this.quantity = quantity;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getWarehouse() {
+ return warehouse;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ void setQuantity(int quantity) {
+ this.quantity = quantity;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/application.properties b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/application.properties
new file mode 100644
index 0000000..4453833
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/application.properties
@@ -0,0 +1,28 @@
+spring.application.name=batch-writes
+
+# Postgres from compose.yaml. Port 5455 so it does not clash with a Postgres you already run.
+# Task 4: reWriteBatchedInserts=true makes the Postgres driver turn a batch of INSERTs into
+# multi-row INSERT statements. (A DB_URL environment variable replaces this whole URL, option included.)
+spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5455/batching?reWriteBatchedInserts=true}
+spring.datasource.username=${DB_USER:batching}
+spring.datasource.password=${DB_PASSWORD:batching}
+
+spring.jpa.hibernate.ddl-auto=none
+spring.jpa.open-in-view=false
+
+# schema.sql drops and creates the tables on every start, so every run begins empty.
+spring.sql.init.mode=always
+
+# Send INSERTs and UPDATEs in JDBC batches of 50 statements.
+spring.jpa.properties.hibernate.jdbc.batch_size=50
+
+# Task 5: sort the INSERTs and UPDATEs of a flush by table, so products and stock levels do not
+# take turns and break every batch.
+spring.jpa.properties.hibernate.order_inserts=true
+spring.jpa.properties.hibernate.order_updates=true
+
+# Counts the entities in the persistence context at every flush. ./demo and the tests read it.
+spring.jpa.properties.hibernate.session_factory.interceptor=com.amigoscode.batching.db.ManagedEntities
+
+# Uncomment to see every SQL statement (or run ./demo --sql).
+# logging.level.org.hibernate.SQL=DEBUG
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/schema.sql
new file mode 100644
index 0000000..b96d81c
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/schema.sql
@@ -0,0 +1,37 @@
+-- Runs on every start, so every run begins with empty tables.
+
+-- Counts every statement Postgres executes. ./demo and ./inspect read it. It needs
+-- shared_preload_libraries=pg_stat_statements, which compose.yaml sets.
+create extension if not exists pg_stat_statements;
+
+drop table if exists stock_level, product, price_change;
+drop sequence if exists product_seq, stock_level_seq;
+
+-- Ids come from sequences that move 50 at a time. Hibernate asks once and uses the 50 values in
+-- memory, so allocationSize = 50 in Product and StockLevel must match INCREMENT BY 50 here.
+create sequence product_seq increment by 50;
+create sequence stock_level_seq increment by 50;
+
+create table product (
+ id bigint primary key default nextval('product_seq'),
+ sku text not null unique,
+ name text not null,
+ price numeric(10,2) not null check (price >= 0)
+);
+
+create table stock_level (
+ id bigint primary key default nextval('stock_level_seq'),
+ product_id bigint not null references product (id),
+ warehouse text not null,
+ quantity int not null check (quantity >= 0)
+);
+
+create index stock_level_product_id on stock_level (product_id);
+
+-- The id is a UUID made in Java (see PriceChange).
+create table price_change (
+ id uuid primary key,
+ sku text not null,
+ price numeric(10,2) not null,
+ changed_at timestamptz not null
+);
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/Check.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/Check.java
new file mode 100644
index 0000000..50781ec
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/Check.java
@@ -0,0 +1,116 @@
+package com.amigoscode.batching;
+
+import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.discovery.ClassNameFilter;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.TagFilter;
+import org.junit.platform.launcher.TestExecutionListener;
+import org.junit.platform.launcher.TestIdentifier;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+
+/**
+ * Runs the tests that belong to one task and prints one line per acceptance criterion.
+ * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2
+ * (./mvnw verify runs the same tests the usual Maven way.)
+ */
+public final class Check {
+
+ /** Tasks that have tests. Task 3 is an inspection task: you answer questions, no code. */
+ private static final Map TASKS = new LinkedHashMap<>();
+
+ static {
+ TASKS.put("baseline", "Baseline: the CSV format and the HTTP contract (passes from the start, must stay green)");
+ TASKS.put("1", "Task 1: See 10,000 round trips");
+ TASKS.put("2", "Task 2: Let Hibernate batch: SEQUENCE instead of IDENTITY");
+ TASKS.put("4", "Task 4: Multi-row INSERTs: reWriteBatchedInserts");
+ TASKS.put("5", "Task 5: Parents and children: order_inserts and order_updates");
+ TASKS.put("6", "Task 6: Flat memory: flush and clear");
+ TASKS.put("7", "Task 7: Ids made in Java: no SELECT before every INSERT");
+ TASKS.put("8", "Task 8: Leave JPA: JdbcTemplate and COPY");
+ }
+
+ public static void main(String[] args) {
+ if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) {
+ System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything.");
+ System.exit(2);
+ }
+ if (args.length == 1 && !TASKS.containsKey(args[0])) {
+ System.out.println();
+ System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:");
+ System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions.");
+ System.out.println();
+ return;
+ }
+
+ boolean allGreen = true;
+ Launcher launcher = LauncherFactory.create();
+ for (Map.Entry task : TASKS.entrySet()) {
+ if (args.length == 1 && !task.getKey().equals(args[0])) {
+ continue;
+ }
+ String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey();
+ LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectPackage(Check.class.getPackageName()))
+ .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag))
+ .build();
+ System.out.println();
+ System.out.println(task.getValue());
+ Results results = new Results();
+ launcher.execute(request, results);
+ System.out.println(" " + results.passed + " of " + results.total + " pass");
+ allGreen &= results.passed == results.total && results.total > 0;
+ }
+ System.out.println();
+ System.exit(allGreen ? 0 : 1);
+ }
+
+ private static final class Results implements TestExecutionListener {
+
+ private int total;
+ private int passed;
+
+ @Override
+ public void executionFinished(TestIdentifier test, TestExecutionResult result) {
+ boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL;
+ if (!test.isTest()) {
+ // A container that fails (for example the Spring context cannot start) takes its tests with it.
+ if (!ok) {
+ total++;
+ System.out.println(" [FAIL] " + test.getDisplayName() + " could not start");
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ return;
+ }
+ total++;
+ if (ok) {
+ passed++;
+ System.out.println(" [PASS] " + test.getDisplayName());
+ } else {
+ System.out.println(" [FAIL] " + test.getDisplayName());
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ }
+
+ private static void printReason(Throwable throwable) {
+ Throwable root = throwable;
+ while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) {
+ root = root.getCause();
+ }
+ String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage();
+ message.strip().lines()
+ .map(String::strip)
+ .filter(line -> !line.isEmpty())
+ .limit(6)
+ .forEach(line -> System.out.println(" " + line));
+ }
+ }
+
+ private Check() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ImportControllerTest.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ImportControllerTest.java
new file mode 100644
index 0000000..6dca681
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ImportControllerTest.java
@@ -0,0 +1,95 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.amigoscode.batching.imports.ImportController;
+import com.amigoscode.batching.imports.ImportService;
+import com.amigoscode.batching.imports.ImportStrategy;
+import com.amigoscode.batching.product.ProductRow;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+/**
+ * Unit tests for the HTTP contract: no Spring context, no database, ImportService is a stub. They
+ * pass from the start and must keep passing whatever you change behind the controller.
+ */
+@Tag("baseline")
+class ImportControllerTest {
+
+ private static final String CSV = "sku,name,price\nSKU-1,Mug,7.50\nSKU-2,Kettle,24.00\n";
+
+ @Test
+ @DisplayName("HTTP: POST /api/imports/products reads the CSV row by row and returns how many rows were imported")
+ void importReturnsTheRowCount() throws Exception {
+ List received = new ArrayList<>();
+ ImportStrategy[] strategy = new ImportStrategy[1];
+
+ api((chosen, rows) -> {
+ strategy[0] = chosen;
+ rows.forEach(received::add);
+ return received.size();
+ }).perform(post("/api/imports/products?strategy=copy").contentType("text/csv").content(CSV))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.strategy").value("copy"))
+ .andExpect(jsonPath("$.rows").value(2));
+
+ assertThat(strategy[0]).isEqualTo(ImportStrategy.COPY);
+ assertThat(received).extracting(ProductRow::sku).containsExactly("SKU-1", "SKU-2");
+ }
+
+ @Test
+ @DisplayName("HTTP: an unknown strategy returns 400 UNKNOWN_STRATEGY")
+ void unknownStrategy() throws Exception {
+ api((chosen, rows) -> 0).perform(post("/api/imports/products?strategy=faster").contentType("text/csv").content(CSV))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.code").value("UNKNOWN_STRATEGY"));
+ }
+
+ @Test
+ @DisplayName("HTTP: a row that cannot be read returns 400 BAD_CSV with its line number")
+ void badRow() throws Exception {
+ api((chosen, rows) -> {
+ rows.forEach(row -> { });
+ return 0;
+ }).perform(post("/api/imports/products").contentType("text/csv").content(CSV + "SKU-3,Lamp,cheap\n"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.code").value("BAD_CSV"))
+ .andExpect(jsonPath("$.line").value(4));
+ }
+
+ @Test
+ @DisplayName("HTTP: a row the database refuses returns 422 IMPORT_REJECTED")
+ void rejectedRow() throws Exception {
+ api((chosen, rows) -> {
+ throw new DataIntegrityViolationException("new row violates check constraint \"product_price_check\"");
+ }).perform(post("/api/imports/products").contentType("text/csv").content(CSV))
+ .andExpect(status().isUnprocessableContent())
+ .andExpect(jsonPath("$.code").value("IMPORT_REJECTED"));
+ }
+
+ private interface Importer {
+ long run(ImportStrategy strategy, Iterable rows);
+ }
+
+ /** The controller wired to an ImportService whose importProducts does whatever the test says. */
+ private static MockMvc api(Importer importer) {
+ ImportService stub = new ImportService(null, null, null) {
+ @Override
+ public long importProducts(ImportStrategy strategy, Iterable rows) {
+ return importer.run(strategy, rows);
+ }
+ };
+ return MockMvcBuilders.standaloneSetup(new ImportController(stub))
+ .setControllerAdvice(new ApiExceptionHandler())
+ .build();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/JdbcImportIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/JdbcImportIT.java
new file mode 100644
index 0000000..ae14e93
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/JdbcImportIT.java
@@ -0,0 +1,88 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.db.SqlCall;
+import com.amigoscode.batching.product.ProductRow;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** No JPA: JdbcTemplate.batchUpdate and Postgres COPY. */
+@Tag("task8")
+class JdbcImportIT extends IntegrationTest {
+
+ /** A comma, double quotes, a backslash, a line break and a tab: everything that breaks hand-made CSV. */
+ private static final String AWKWARD_NAME = "Mug, \"large\"\\0.5 l\nsecond line\tand a tab";
+
+ @Test
+ @DisplayName("JdbcTemplate: 2,000 products in 40 round trips, batches of 50")
+ void jdbcTemplateSendsBatches() {
+ Recording recording = record(() -> jdbcImporter.batchInsert(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(40);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("JdbcTemplate: a name with commas, quotes, a backslash and a line break is stored exactly as sent")
+ void jdbcTemplateStoresAwkwardNames() {
+ jdbcImporter.batchInsert(List.of(new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50"))));
+
+ assertThat(jdbc.queryForObject("select name from product", String.class)).isEqualTo(AWKWARD_NAME);
+ }
+
+ @Test
+ @DisplayName("COPY: 2,000 products in one statement")
+ void copyIsOneStatement() {
+ Recording recording = record(() -> jdbcImporter.copy(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(1);
+ assertThat(recording.calls().getFirst().kind()).as("kind of round trip").isEqualTo(SqlCall.Kind.COPY);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("COPY: a name with commas, quotes, a backslash and a line break is stored exactly as sent")
+ void copyStoresAwkwardNames() {
+ List rows = List.of(
+ new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50")),
+ new ProductRow("SKU-2", "Plain name", new BigDecimal("1.00")));
+
+ try {
+ jdbcImporter.copy(rows);
+ } catch (RuntimeException e) {
+ throw new AssertionError("COPY refused the rows: " + rootMessage(e), e);
+ }
+
+ assertThat(jdbc.queryForList("select name from product order by sku", String.class))
+ .containsExactly(AWKWARD_NAME, "Plain name");
+ }
+
+ @Test
+ @DisplayName("COPY: one bad row (a negative price) and nothing is stored, not even the rows before it")
+ void oneBadRowStopsTheWholeCopy() {
+ List rows = new ArrayList<>(Rows.products(2_000));
+ rows.set(1_500, new ProductRow("SKU-1501", "Product 1501", new BigDecimal("-1.00")));
+
+ assertThatThrownBy(() -> jdbcImporter.copy(rows)).as("a negative price is refused by the database");
+
+ assertThat(count("product")).as("products stored").isZero();
+ }
+
+ private static String rootMessage(Throwable e) {
+ Throwable root = e;
+ while (root.getCause() != null && root.getCause() != root) {
+ root = root.getCause();
+ }
+ return root.getMessage();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/OneByOneIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/OneByOneIT.java
new file mode 100644
index 0000000..ad70242
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/OneByOneIT.java
@@ -0,0 +1,42 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.product.ProductRow;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Task 1. These tests pass on purpose: they pin down the problem so you can see what the fixes change. */
+@Tag("task1")
+class OneByOneIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("One by one: 500 rows are 500 INSERTs, each in its own round trip and its own transaction (this documents the problem)")
+ void everyRowIsItsOwnRoundTripAndTransaction() {
+ Recording recording = record(() -> productImporter.importOneByOne(Rows.products(500)));
+
+ assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(500);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(1);
+ assertThat(recording.commits()).as("commits").isEqualTo(500);
+ assertThat(count("product")).as("products stored").isEqualTo(500);
+ }
+
+ @Test
+ @DisplayName("One by one: a bad row in the middle leaves every row before it in the database (this documents the problem)")
+ void aBadRowLeavesHalfAnImport() {
+ List rows = new ArrayList<>(Rows.products(100));
+ rows.set(60, new ProductRow("SKU-61", "Product 61", new BigDecimal("-1.00")));
+
+ assertThatThrownBy(() -> productImporter.importOneByOne(rows)).as("a negative price is refused by the database");
+
+ assertThat(count("product")).as("products left behind by a failed import").isEqualTo(60);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java
new file mode 100644
index 0000000..cee1bca
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java
@@ -0,0 +1,68 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** 500 products with 3 stock levels each: 500 parents and 1,500 children saved in one go. */
+@Tag("task5")
+class ParentsAndChildrenIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Insert: 500 products and 1,500 stock levels go in full batches: 10 product batches and 30 stock level batches")
+ void insertsAreSortedIntoFullBatches() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0)));
+
+ String sent = "\n" + recording.describe();
+ assertThat(recording.roundTrips("insert into product")).as("product INSERT round trips" + sent).isLessThanOrEqualTo(10);
+ assertThat(recording.roundTrips("insert into stock_level")).as("stock level INSERT round trips" + sent).isLessThanOrEqualTo(30);
+ }
+
+ @Test
+ @DisplayName("Insert: stock levels get their ids from a sequence too, at most 31 nextval calls for 1,500 of them")
+ void stockLevelIdsComeFromASequence() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0)));
+
+ assertThat(recording.roundTrips("select nextval('stock_level_seq')"))
+ .as("nextval('stock_level_seq') round trips\n" + recording.describe()).isBetween(1, 31);
+ }
+
+ @Test
+ @DisplayName("Update: a new price and new stock for 500 products takes at most 40 UPDATE round trips, not 1,000")
+ void updatesAreSortedIntoFullBatches() {
+ productImporter.importBatched(Rows.productsWithStock(500, 0));
+
+ Recording recording = record(() -> productImporter.updateAll(Rows.productsWithStock(500, 1)));
+
+ assertThat(recording.roundTrips("update")).as("UPDATE round trips\n" + recording.describe()).isLessThanOrEqualTo(40);
+ assertThat(stockLevelsMatching(1)).as("stock levels that now hold the next day's quantity").isEqualTo(1_500);
+ // Every price went up by 1.00: 1.01 + ... + 6.00 is 1,752.50, plus 500 x 1.00.
+ assertThat(jdbc.queryForObject("select sum(price) from product", java.math.BigDecimal.class))
+ .as("sum of the new prices").isEqualByComparingTo("2252.50");
+ }
+
+ @Test
+ @DisplayName("Insert: every stock level is stored and points to its own product")
+ void everyStockLevelBelongsToItsProduct() {
+ productImporter.importBatched(Rows.productsWithStock(500, 0));
+
+ assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500);
+ assertThat(stockLevelsMatching(0)).as("stock levels whose quantity matches their own product's row").isEqualTo(1_500);
+ }
+
+ /** Stock levels whose quantity is what Rows.productsWithStock(.., day) gave their product. */
+ private long stockLevelsMatching(int day) {
+ return jdbc.queryForObject("""
+ select count(*)
+ from stock_level s
+ join product p on p.id = s.product_id
+ where s.quantity = (cast(substring(p.sku from 5) as int)
+ + ? * case s.warehouse when 'GLA' then 1 when 'LON' then 2 else 3 end) % 10
+ """, Long.class, day);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PersistenceContextIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PersistenceContextIT.java
new file mode 100644
index 0000000..65f3115
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PersistenceContextIT.java
@@ -0,0 +1,63 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.db.ManagedEntities;
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.product.ProductRow;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/**
+ * ManagedEntities counts the entities in the persistence context every time Hibernate flushes.
+ * Every managed entity stays in memory, with a copy of its values for dirty checking, until the
+ * transaction ends or the persistence context is cleared.
+ */
+@Tag("task6")
+class PersistenceContextIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Memory: importing 2,000 products never holds more than 50 entities in the persistence context")
+ void productsAreNotKeptInMemory() {
+ record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(50);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("Memory: with stock levels, never more than 200 entities (50 products and their 150 stock levels)")
+ void productsWithStockAreNotKeptInMemory() {
+ record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0)));
+
+ assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(200);
+ assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500);
+ }
+
+ @Test
+ @DisplayName("Memory: clearing every 50 rows keeps the batches full: still 40 INSERT batches of 50 for 2,000 products")
+ void clearingKeepsTheBatchesFull() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50);
+ }
+
+ @Test
+ @DisplayName("Memory: flush is not commit: a bad row near the end still rolls back the whole import")
+ void flushIsNotCommit() {
+ List rows = new ArrayList<>(Rows.products(2_000));
+ rows.set(1_900, new ProductRow("SKU-1901", "Product 1901", new BigDecimal("-1.00")));
+
+ assertThatThrownBy(() -> productImporter.importBatched(rows)).as("a negative price is refused by the database");
+
+ assertThat(count("product")).as("products left behind by a failed import").isZero();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PriceHistoryIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PriceHistoryIT.java
new file mode 100644
index 0000000..82a6e87
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PriceHistoryIT.java
@@ -0,0 +1,64 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.price.PriceChange;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/** PriceChange ids are UUIDs made in Java, so the id is never null, not even before the first save. */
+@Tag("task7")
+class PriceHistoryIT extends IntegrationTest {
+
+ @Autowired
+ private TransactionTemplate transaction;
+
+ @Test
+ @DisplayName("Assigned ids: saving 1,000 price changes sends no SELECT, only 20 INSERT batches")
+ void noSelectBeforeEveryInsert() {
+ Recording recording = record(() -> priceHistory.record(Rows.products(1_000)));
+
+ String sent = "\n" + recording.describe();
+ assertThat(recording.roundTrips("select")).as("SELECT round trips" + sent).isZero();
+ assertThat(recording.roundTrips("insert into price_change")).as("INSERT round trips" + sent).isEqualTo(20);
+ assertThat(count("price_change")).as("price changes stored").isEqualTo(1_000);
+ }
+
+ @Test
+ @DisplayName("Assigned ids: saveAll() returns the objects you gave it (persist), not copies of them (merge)")
+ void saveAllPersistsTheSameObjects() {
+ List changes = List.of(
+ new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now()),
+ new PriceChange("SKU-2", new BigDecimal("2.00"), Instant.now()));
+
+ List saved = transaction.execute(status -> priceChanges.saveAll(changes));
+
+ assertThat(saved).as("what saveAll returned").hasSize(2);
+ assertThat(saved.get(0)).as("the first object saveAll returned").isSameAs(changes.get(0));
+ assertThat(saved.get(1)).as("the second object saveAll returned").isSameAs(changes.get(1));
+ }
+
+ @Test
+ @DisplayName("Assigned ids: a price change loaded from the database and saved again is updated, not inserted a second time")
+ void aLoadedPriceChangeIsUpdated() {
+ PriceChange original = new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now());
+ transaction.executeWithoutResult(status -> priceChanges.save(original));
+
+ PriceChange loaded = priceChanges.findById(original.getId()).orElseThrow();
+ loaded.setPrice(new BigDecimal("1.50"));
+ transaction.executeWithoutResult(status -> priceChanges.save(loaded));
+
+ assertThat(count("price_change")).as("price change rows").isEqualTo(1);
+ assertThat(jdbc.queryForObject("select price from price_change", BigDecimal.class)).as("the stored price")
+ .isEqualByComparingTo("1.50");
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ProductCsvTest.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ProductCsvTest.java
new file mode 100644
index 0000000..6014c02
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ProductCsvTest.java
@@ -0,0 +1,60 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.imports.BadCsvException;
+import com.amigoscode.batching.imports.ProductCsv;
+import com.amigoscode.batching.product.ProductRow;
+import java.io.StringReader;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Unit tests: no Spring, no database. The feed format, which none of the tasks change. */
+@Tag("baseline")
+class ProductCsvTest {
+
+ @Test
+ @DisplayName("CSV: quoted fields keep their commas, quotes and line breaks")
+ void quotedFields() {
+ List rows = read("""
+ sku,name,price
+ SKU-1,"Mug, ""large""
+ second line",7.50
+ SKU-2,Plain,1
+ """);
+
+ assertThat(rows).extracting(ProductRow::name).containsExactly("Mug, \"large\"\nsecond line", "Plain");
+ assertThat(rows.get(0).price()).isEqualByComparingTo("7.50");
+ }
+
+ @Test
+ @DisplayName("CSV: every column after price is a warehouse, and its value is the stock there")
+ void warehouseColumns() {
+ List rows = read("""
+ sku,name,price,LON,MAN
+ SKU-1,Mug,7.50,12,3
+ """);
+
+ assertThat(rows.getFirst().stock()).isEqualTo(Map.of("LON", 12, "MAN", 3));
+ }
+
+ @Test
+ @DisplayName("CSV: a price that is not a number is rejected with its line number")
+ void badPrice() {
+ assertThatThrownBy(() -> read("""
+ sku,name,price
+ SKU-1,Mug,7.50
+ SKU-2,Kettle,cheap
+ """))
+ .isInstanceOf(BadCsvException.class)
+ .hasMessageContaining("Line 3");
+ }
+
+ private static List read(String csv) {
+ return ProductCsv.read(new StringReader(csv)).toList();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/RewriteIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/RewriteIT.java
new file mode 100644
index 0000000..3be1280
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/RewriteIT.java
@@ -0,0 +1,54 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import com.amigoscode.batching.support.ServerSide;
+import java.math.BigDecimal;
+import java.sql.Connection;
+import javax.sql.DataSource;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.postgresql.core.BaseConnection;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Tag("task4")
+class RewriteIT extends IntegrationTest {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Test
+ @DisplayName("Driver: the connections of the pool have reWriteBatchedInserts switched on")
+ void theDriverRewritesBatches() throws Exception {
+ try (Connection connection = dataSource.getConnection()) {
+ boolean rewrite = connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled();
+
+ assertThat(rewrite).as("reWriteBatchedInserts, as the Postgres driver sees it").isTrue();
+ }
+ }
+
+ @Test
+ @DisplayName("Postgres: 2,000 products arrive as multi-row INSERTs, at most 200 INSERT executions instead of 2,000")
+ void postgresExecutesMultiRowInserts() {
+ ServerSide.Executed executed = onTheServer(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(executed.rows("insert into product")).as("rows inserted\n" + executed.describe()).isEqualTo(2_000);
+ assertThat(executed.executions("insert into product")).as("INSERT statements Postgres executed\n" + executed.describe())
+ .isLessThanOrEqualTo(200);
+ }
+
+ @Test
+ @DisplayName("Postgres: every row still arrives exactly once (2,000 rows, and the prices add up)")
+ void everyRowArrivesOnce() {
+ productImporter.importBatched(Rows.products(2_000));
+
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ assertThat(jdbc.queryForObject("select count(distinct sku) from product", Long.class)).as("distinct SKUs").isEqualTo(2_000);
+ // 1.01 + 1.02 + ... + 21.00
+ assertThat(jdbc.queryForObject("select sum(price) from product", BigDecimal.class)).as("sum of the prices")
+ .isEqualByComparingTo("22010.00");
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/SequenceIdsIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/SequenceIdsIT.java
new file mode 100644
index 0000000..bfc5189
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/SequenceIdsIT.java
@@ -0,0 +1,68 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.product.Product;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import jakarta.persistence.EntityManagerFactory;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.generator.Generator;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Tag("task2")
+class SequenceIdsIT extends IntegrationTest {
+
+ @Autowired
+ private EntityManagerFactory entityManagerFactory;
+
+ @Test
+ @DisplayName("Batched: 2,000 products are sent as 40 INSERT batches of 50, not 2,000 single INSERTs")
+ void insertsAreSentInBatches() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("Batched: the ids come from a sequence, 50 at a time: at most 41 nextval calls for 2,000 products")
+ void idsComeFromTheSequenceFiftyAtATime() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips("select nextval")).as("nextval round trips\n" + recording.describe())
+ .isBetween(1, 41);
+ }
+
+ @Test
+ @DisplayName("Mapping: Product uses a SEQUENCE generator whose allocationSize equals the sequence's INCREMENT BY")
+ void allocationSizeMatchesTheSequence() {
+ Generator generator = entityManagerFactory.unwrap(SessionFactoryImplementor.class)
+ .getMappingMetamodel().getEntityDescriptor(Product.class).getGenerator();
+
+ assertThat(generator).as("the id generator of Product").isInstanceOf(SequenceStyleGenerator.class);
+ SequenceStyleGenerator sequence = (SequenceStyleGenerator) generator;
+ String name = sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText();
+ Long incrementBy = jdbc.queryForObject("select increment_by from pg_sequences where sequencename = ?", Long.class, name);
+ assertThat(sequence.getOptimizer().getIncrementSize()).as("allocationSize of " + name)
+ .isGreaterThan(1)
+ .isEqualTo(incrementBy.intValue());
+ }
+
+ @Test
+ @DisplayName("Ids: two imports with a plain SQL INSERT in between never hand out the same id twice")
+ void idsNeverClash() {
+ productImporter.importBatched(Rows.products(1_000, "A-"));
+ jdbc.update("insert into product (sku, name, price) values ('PLAIN-1', 'Inserted with plain SQL', 1.00)");
+ productImporter.importBatched(Rows.products(1_000, "B-"));
+
+ assertThat(jdbc.queryForObject("select count(distinct id) from product", Long.class))
+ .as("distinct ids for 2,001 products").isEqualTo(2_001);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/DriverOptions.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/DriverOptions.java
new file mode 100644
index 0000000..3435396
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/DriverOptions.java
@@ -0,0 +1,40 @@
+package com.amigoscode.batching.support;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.util.Properties;
+
+/**
+ * The tests talk to a Postgres started by Testcontainers, on its own URL. Driver options you add to
+ * spring.datasource.url in application.properties (everything after the "?") are copied onto that
+ * URL, so they apply in the tests exactly as they do in ./demo.
+ */
+final class DriverOptions {
+
+ /** "&reWriteBatchedInserts=true", or "" when the URL in application.properties has no options. */
+ static String fromApplicationProperties() {
+ Properties properties = new Properties();
+ try (InputStream in = DriverOptions.class.getResourceAsStream("/application.properties")) {
+ if (in == null) {
+ return "";
+ }
+ properties.load(in);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ String url = properties.getProperty("spring.datasource.url", "");
+ int query = url.indexOf('?');
+ if (query < 0) {
+ return "";
+ }
+ String options = url.substring(query + 1);
+ if (options.endsWith("}")) {
+ options = options.substring(0, options.length() - 1);
+ }
+ return options.isBlank() ? "" : "&" + options;
+ }
+
+ private DriverOptions() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/IntegrationTest.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/IntegrationTest.java
new file mode 100644
index 0000000..9fa6df2
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/IntegrationTest.java
@@ -0,0 +1,86 @@
+package com.amigoscode.batching.support;
+
+import com.amigoscode.batching.db.ManagedEntities;
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.db.SqlRecorder;
+import com.amigoscode.batching.price.PriceChangeRepository;
+import com.amigoscode.batching.price.PriceHistory;
+import com.amigoscode.batching.product.JdbcProductImporter;
+import com.amigoscode.batching.product.ProductImporter;
+import org.junit.jupiter.api.BeforeEach;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.testcontainers.postgresql.PostgreSQLContainer;
+
+/**
+ * Base class for the *IT tests. They run the real application against a real Postgres started by
+ * Testcontainers (Docker must be running), because how many round trips an import makes is decided
+ * by Hibernate, the mapping and the JDBC driver together, and no mock can tell you that. One
+ * container is shared by every test class.
+ *
+ * The tests never measure time. They count: round trips to the database (SqlRecorder), statements
+ * Postgres executed (pg_stat_statements), entities in the persistence context (ManagedEntities) and
+ * rows in the tables.
+ */
+@SpringBootTest(properties = "spring.main.banner-mode=off")
+public abstract class IntegrationTest {
+
+ private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine")
+ .withCommand("postgres", "-c", "fsync=off", "-c", "shared_preload_libraries=pg_stat_statements");
+
+ static {
+ POSTGRES.start();
+ }
+
+ @DynamicPropertySource
+ static void database(DynamicPropertyRegistry registry) {
+ registry.add("spring.datasource.url", () -> POSTGRES.getJdbcUrl() + DriverOptions.fromApplicationProperties());
+ registry.add("spring.datasource.username", POSTGRES::getUsername);
+ registry.add("spring.datasource.password", POSTGRES::getPassword);
+ }
+
+ @Autowired
+ protected ProductImporter productImporter;
+
+ @Autowired
+ protected JdbcProductImporter jdbcImporter;
+
+ @Autowired
+ protected PriceHistory priceHistory;
+
+ @Autowired
+ protected PriceChangeRepository priceChanges;
+
+ @Autowired
+ protected JdbcTemplate jdbc;
+
+ @BeforeEach
+ void emptyTables() {
+ jdbc.execute("truncate table stock_level, product, price_change");
+ }
+
+ /** Runs the work and returns every round trip it made to Postgres. */
+ protected Recording record(Runnable work) {
+ ManagedEntities.reset();
+ SqlRecorder.start();
+ try {
+ work.run();
+ } catch (RuntimeException e) {
+ SqlRecorder.stop();
+ throw e;
+ }
+ return SqlRecorder.stop();
+ }
+
+ /** Runs the work and returns what Postgres itself executed while it ran (pg_stat_statements). */
+ protected ServerSide.Executed onTheServer(Runnable work) {
+ return ServerSide.during(jdbc, work);
+ }
+
+ protected long count(String table) {
+ return jdbc.queryForObject("select count(*) from " + table, Long.class);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/Rows.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/Rows.java
new file mode 100644
index 0000000..8153d92
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/Rows.java
@@ -0,0 +1,42 @@
+package com.amigoscode.batching.support;
+
+import com.amigoscode.batching.product.ProductRow;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/** Rows of a feed, made up in the test. */
+public final class Rows {
+
+ public static List products(int count) {
+ return products(count, "SKU-");
+ }
+
+ /** Different prefixes give different SKUs, so two imports in one test do not clash. */
+ public static List products(int count, String skuPrefix) {
+ List rows = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ rows.add(new ProductRow(skuPrefix + i, "Product " + i, price(i)));
+ }
+ return rows;
+ }
+
+ /** Every product with stock in three warehouses. {@code day} changes the price and the stock. */
+ public static List productsWithStock(int count, int day) {
+ List rows = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ rows.add(new ProductRow("SKU-" + i, "Product " + i, price(i).add(BigDecimal.valueOf(day)),
+ Map.of("GLA", (i + day) % 10, "LON", (i + 2 * day) % 10, "MAN", (i + 3 * day) % 10)));
+ }
+ return rows;
+ }
+
+ /** 1.00, 1.01, ... so the total of the prices tells you whether every row arrived once. */
+ public static BigDecimal price(int i) {
+ return BigDecimal.valueOf(100 + i, 2);
+ }
+
+ private Rows() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/ServerSide.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/ServerSide.java
new file mode 100644
index 0000000..83831bd
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/ServerSide.java
@@ -0,0 +1,53 @@
+package com.amigoscode.batching.support;
+
+import java.util.List;
+import java.util.Locale;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/** What Postgres itself executed, read from pg_stat_statements. */
+public final class ServerSide {
+
+ /** One statement as Postgres normalised it, how many times it ran, and how many rows it touched. */
+ public record Statement(String query, long executions, long rows) {
+ }
+
+ public record Executed(List statements) {
+
+ /** How many times Postgres ran a statement that starts with the prefix, for example "insert into product". */
+ public long executions(String prefix) {
+ return matching(prefix).stream().mapToLong(Statement::executions).sum();
+ }
+
+ public long rows(String prefix) {
+ return matching(prefix).stream().mapToLong(Statement::rows).sum();
+ }
+
+ private List matching(String prefix) {
+ return statements.stream()
+ .filter(statement -> statement.query().toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT)))
+ .toList();
+ }
+
+ public String describe() {
+ StringBuilder text = new StringBuilder("Postgres executed:");
+ statements.forEach(statement -> text.append(String.format("%n%,d x %s", statement.executions(),
+ statement.query().length() > 90 ? statement.query().substring(0, 90) + "..." : statement.query())));
+ return text.toString();
+ }
+ }
+
+ static Executed during(JdbcTemplate jdbc, Runnable work) {
+ jdbc.execute("select pg_stat_statements_reset()");
+ work.run();
+ return new Executed(jdbc.query("""
+ select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows
+ from pg_stat_statements
+ where dbid = (select oid from pg_database where datname = current_database())
+ and query !~* 'pg_stat_statements'
+ order by calls desc
+ """, (row, number) -> new Statement(row.getString(1), row.getLong(2), row.getLong(3))));
+ }
+
+ private ServerSide() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/16-batch-writes/solution/src/test/resources/logback-test.xml
new file mode 100644
index 0000000..82166a4
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/resources/logback-test.xml
@@ -0,0 +1,11 @@
+
+
+
+ %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n
+
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/16-batch-writes/start/.mvn/jvm.config b/java/concepts/junior-mid/16-batch-writes/start/.mvn/jvm.config
new file mode 100644
index 0000000..07a2d88
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/.mvn/jvm.config
@@ -0,0 +1,2 @@
+--enable-native-access=ALL-UNNAMED
+--sun-misc-unsafe-memory-access=allow
diff --git a/java/concepts/junior-mid/16-batch-writes/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/16-batch-writes/start/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ffcab66
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,3 @@
+wrapperVersion=3.3.4
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
diff --git a/java/concepts/junior-mid/16-batch-writes/start/check b/java/concepts/junior-mid/16-batch-writes/start/check
new file mode 100755
index 0000000..8ecf048
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/check
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use check.cmd (type: .\check).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.batching.Check -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/check.cmd b/java/concepts/junior-mid/16-batch-writes/start/check.cmd
new file mode 100644
index 0000000..3c5f22a
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/check.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./check
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.batching.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/compose.yaml b/java/concepts/junior-mid/16-batch-writes/start/compose.yaml
new file mode 100644
index 0000000..b4d4314
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/compose.yaml
@@ -0,0 +1,21 @@
+# The project name is set here because the folder is called "solution" (or "start") in every
+# project of this repository: without it, "docker compose down" in another project would stop this one.
+name: batch-writes
+services:
+ postgres:
+ image: postgres:17-alpine
+ container_name: batch-writes-postgres
+ # pg_stat_statements counts every statement Postgres executes. ./demo and ./inspect read it to
+ # show what the database really received, which is not always what the application sent.
+ command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "pg_stat_statements.track=all"]
+ environment:
+ POSTGRES_DB: batching
+ POSTGRES_USER: batching
+ POSTGRES_PASSWORD: batching
+ ports:
+ - "5455:5432"
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U batching -d batching"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
diff --git a/java/concepts/junior-mid/16-batch-writes/start/demo b/java/concepts/junior-mid/16-batch-writes/start/demo
new file mode 100755
index 0000000..4b092c3
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/demo
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.batching.demo.Demo -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/demo.cmd b/java/concepts/junior-mid/16-batch-writes/start/demo.cmd
new file mode 100644
index 0000000..4c7d257
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/demo.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./demo
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.batching.demo.Demo" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/inspect b/java/concepts/junior-mid/16-batch-writes/start/inspect
new file mode 100755
index 0000000..b86b2a6
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/inspect
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.batching.demo.Inspect -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/inspect.cmd b/java/concepts/junior-mid/16-batch-writes/start/inspect.cmd
new file mode 100644
index 0000000..fbf084b
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/inspect.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./inspect
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.batching.demo.Inspect" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/mvnw b/java/concepts/junior-mid/16-batch-writes/start/mvnw
new file mode 100755
index 0000000..bd8896b
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/mvnw
@@ -0,0 +1,295 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Apache Maven Wrapper startup batch script, version 3.3.4
+#
+# Optional ENV vars
+# -----------------
+# JAVA_HOME - location of a JDK home dir, required when download maven via java source
+# MVNW_REPOURL - repo url base for downloading maven distribution
+# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
+# ----------------------------------------------------------------------------
+
+set -euf
+[ "${MVNW_VERBOSE-}" != debug ] || set -x
+
+# OS specific support.
+native_path() { printf %s\\n "$1"; }
+case "$(uname)" in
+CYGWIN* | MINGW*)
+ [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
+ native_path() { cygpath --path --windows "$1"; }
+ ;;
+esac
+
+# set JAVACMD and JAVACCMD
+set_java_home() {
+ # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
+ if [ -n "${JAVA_HOME-}" ]; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ]; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ JAVACCMD="$JAVA_HOME/jre/sh/javac"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ JAVACCMD="$JAVA_HOME/bin/javac"
+
+ if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
+ echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
+ echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
+ return 1
+ fi
+ fi
+ else
+ JAVACMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v java
+ )" || :
+ JAVACCMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v javac
+ )" || :
+
+ if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
+ echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
+ return 1
+ fi
+ fi
+}
+
+# hash string like Java String::hashCode
+hash_string() {
+ str="${1:-}" h=0
+ while [ -n "$str" ]; do
+ char="${str%"${str#?}"}"
+ h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
+ str="${str#?}"
+ done
+ printf %x\\n $h
+}
+
+verbose() { :; }
+[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
+
+die() {
+ printf %s\\n "$1" >&2
+ exit 1
+}
+
+trim() {
+ # MWRAPPER-139:
+ # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
+ # Needed for removing poorly interpreted newline sequences when running in more
+ # exotic environments such as mingw bash on Windows.
+ printf "%s" "${1}" | tr -d '[:space:]'
+}
+
+scriptDir="$(dirname "$0")"
+scriptName="$(basename "$0")"
+
+# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
+while IFS="=" read -r key value; do
+ case "${key-}" in
+ distributionUrl) distributionUrl=$(trim "${value-}") ;;
+ distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
+ esac
+done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+
+case "${distributionUrl##*/}" in
+maven-mvnd-*bin.*)
+ MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
+ case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
+ *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
+ :Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
+ :Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
+ :Linux*x86_64*) distributionPlatform=linux-amd64 ;;
+ *)
+ echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
+ distributionPlatform=linux-amd64
+ ;;
+ esac
+ distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
+ ;;
+maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
+*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
+esac
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
+[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
+distributionUrlName="${distributionUrl##*/}"
+distributionUrlNameMain="${distributionUrlName%.*}"
+distributionUrlNameMain="${distributionUrlNameMain%-bin}"
+MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
+MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
+
+exec_maven() {
+ unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
+ exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
+}
+
+if [ -d "$MAVEN_HOME" ]; then
+ verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ exec_maven "$@"
+fi
+
+case "${distributionUrl-}" in
+*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
+*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
+esac
+
+# prepare tmp dir
+if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
+ clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
+ trap clean HUP INT TERM EXIT
+else
+ die "cannot create temp dir"
+fi
+
+mkdir -p -- "${MAVEN_HOME%/*}"
+
+# Download and Install Apache Maven
+verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+verbose "Downloading from: $distributionUrl"
+verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+# select .zip or .tar.gz
+if ! command -v unzip >/dev/null; then
+ distributionUrl="${distributionUrl%.zip}.tar.gz"
+ distributionUrlName="${distributionUrl##*/}"
+fi
+
+# verbose opt
+__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
+[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
+
+# normalize http auth
+case "${MVNW_PASSWORD:+has-password}" in
+'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+esac
+
+if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
+ verbose "Found wget ... using wget"
+ wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
+elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
+ verbose "Found curl ... using curl"
+ curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
+elif set_java_home; then
+ verbose "Falling back to use Java to download"
+ javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
+ targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
+ cat >"$javaSource" <<-END
+ public class Downloader extends java.net.Authenticator
+ {
+ protected java.net.PasswordAuthentication getPasswordAuthentication()
+ {
+ return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
+ }
+ public static void main( String[] args ) throws Exception
+ {
+ setDefault( new Downloader() );
+ java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
+ }
+ }
+ END
+ # For Cygwin/MinGW, switch paths to Windows format before running javac and java
+ verbose " - Compiling Downloader.java ..."
+ "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
+ verbose " - Running Downloader.java ..."
+ "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
+fi
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+if [ -n "${distributionSha256Sum-}" ]; then
+ distributionSha256Result=false
+ if [ "$MVN_CMD" = mvnd.sh ]; then
+ echo "Checksum validation is not supported for maven-mvnd." >&2
+ echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ elif command -v sha256sum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ elif command -v shasum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ else
+ echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
+ echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ fi
+ if [ $distributionSha256Result = false ]; then
+ echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
+ echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
+ exit 1
+ fi
+fi
+
+# unzip and move
+if command -v unzip >/dev/null; then
+ unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
+else
+ tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
+fi
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+actualDistributionDir=""
+
+# First try the expected directory name (for regular distributions)
+if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
+ if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$distributionUrlNameMain"
+ fi
+fi
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if [ -z "$actualDistributionDir" ]; then
+ # enable globbing to iterate over items
+ set +f
+ for dir in "$TMP_DOWNLOAD_DIR"/*; do
+ if [ -d "$dir" ]; then
+ if [ -f "$dir/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$(basename "$dir")"
+ break
+ fi
+ fi
+ done
+ set -f
+fi
+
+if [ -z "$actualDistributionDir" ]; then
+ verbose "Contents of $TMP_DOWNLOAD_DIR:"
+ verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
+ die "Could not find Maven distribution directory in extracted archive"
+fi
+
+verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/mvnw.cmd b/java/concepts/junior-mid/16-batch-writes/start/mvnw.cmd
new file mode 100644
index 0000000..92450f9
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/mvnw.cmd
@@ -0,0 +1,189 @@
+<# : batch portion
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Apache Maven Wrapper startup batch script, version 3.3.4
+@REM
+@REM Optional ENV vars
+@REM MVNW_REPOURL - repo url base for downloading maven distribution
+@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
+@REM ----------------------------------------------------------------------------
+
+@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
+@SET __MVNW_CMD__=
+@SET __MVNW_ERROR__=
+@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
+@SET PSModulePath=
+@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
+ IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
+)
+@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
+@SET __MVNW_PSMODULEP_SAVE=
+@SET __MVNW_ARG0_NAME__=
+@SET MVNW_USERNAME=
+@SET MVNW_PASSWORD=
+@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
+@echo Cannot start maven from wrapper >&2 && exit /b 1
+@GOTO :EOF
+: end batch / begin powershell #>
+
+$ErrorActionPreference = "Stop"
+if ($env:MVNW_VERBOSE -eq "true") {
+ $VerbosePreference = "Continue"
+}
+
+# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
+$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
+if (!$distributionUrl) {
+ Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+}
+
+switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
+ "maven-mvnd-*" {
+ $USE_MVND = $true
+ $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
+ $MVN_CMD = "mvnd.cmd"
+ break
+ }
+ default {
+ $USE_MVND = $false
+ $MVN_CMD = $script -replace '^mvnw','mvn'
+ break
+ }
+}
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
+if ($env:MVNW_REPOURL) {
+ $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
+ $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
+}
+$distributionUrlName = $distributionUrl -replace '^.*/',''
+$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
+
+$MAVEN_M2_PATH = "$HOME/.m2"
+if ($env:MAVEN_USER_HOME) {
+ $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
+}
+
+if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
+ New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
+}
+
+$MAVEN_WRAPPER_DISTS = $null
+if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
+ $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
+} else {
+ $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
+}
+
+$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
+$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
+
+if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
+ Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+ exit $?
+}
+
+if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
+ Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
+}
+
+# prepare tmp dir
+$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
+$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
+$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
+trap {
+ if ($TMP_DOWNLOAD_DIR.Exists) {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+ }
+}
+
+New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
+
+# Download and Install Apache Maven
+Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+Write-Verbose "Downloading from: $distributionUrl"
+Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+$webclient = New-Object System.Net.WebClient
+if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
+ $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
+}
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
+if ($distributionSha256Sum) {
+ if ($USE_MVND) {
+ Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
+ }
+ Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
+ if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
+ Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
+ }
+}
+
+# unzip and move
+Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+$actualDistributionDir = ""
+
+# First try the expected directory name (for regular distributions)
+$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
+$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
+if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
+ $actualDistributionDir = $distributionUrlNameMain
+}
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if (!$actualDistributionDir) {
+ Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
+ $testPath = Join-Path $_.FullName "bin/$MVN_CMD"
+ if (Test-Path -Path $testPath -PathType Leaf) {
+ $actualDistributionDir = $_.Name
+ }
+ }
+}
+
+if (!$actualDistributionDir) {
+ Write-Error "Could not find Maven distribution directory in extracted archive"
+}
+
+Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
+try {
+ Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
+} catch {
+ if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
+ Write-Error "fail to move MAVEN_HOME"
+ }
+} finally {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+}
+
+Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
diff --git a/java/concepts/junior-mid/16-batch-writes/start/pom.xml b/java/concepts/junior-mid/16-batch-writes/start/pom.xml
new file mode 100644
index 0000000..60b85e2
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/pom.xml
@@ -0,0 +1,110 @@
+
+
+ 4.0.0
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 4.0.2
+
+
+
+ com.amigoscode
+ batch-writes
+ 0.0.1-SNAPSHOT
+ batch-writes
+ Batch writes: watch 10,000 rows take 10,000 round trips, then make JPA and JDBC batch them
+
+
+ 25
+ 3.5.0
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.postgresql
+
+ postgresql
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc-test
+ test
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.mockito
+ mockito-core
+
+
+ org.mockito
+ mockito-junit-jupiter
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa-test
+ test
+
+
+ org.testcontainers
+ testcontainers-postgresql
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+ false
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java
new file mode 100644
index 0000000..749a0b5
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java
@@ -0,0 +1,40 @@
+package com.amigoscode.batching;
+
+import com.amigoscode.batching.imports.BadCsvException;
+import com.amigoscode.batching.imports.ImportStrategy.UnknownStrategyException;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+/** Anything not listed here becomes a 500. */
+@RestControllerAdvice
+public class ApiExceptionHandler {
+
+ /** {@code line} is the line of the CSV file that was rejected, or null. */
+ public record ApiError(String code, String message, Integer line) {
+ }
+
+ @ExceptionHandler(BadCsvException.class)
+ public ResponseEntity badCsv(BadCsvException e) {
+ return ResponseEntity.badRequest().body(new ApiError("BAD_CSV", e.getMessage(), e.line()));
+ }
+
+ @ExceptionHandler(UnknownStrategyException.class)
+ public ResponseEntity unknownStrategy(UnknownStrategyException e) {
+ return ResponseEntity.badRequest().body(new ApiError("UNKNOWN_STRATEGY", e.getMessage(), null));
+ }
+
+ /** A row the database refused, for example a negative price or a SKU that already exists. */
+ @ExceptionHandler(DataIntegrityViolationException.class)
+ public ResponseEntity rejected(DataIntegrityViolationException e) {
+ String reason = e.getMostSpecificCause().getMessage();
+ return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(new ApiError("IMPORT_REJECTED",
+ "Nothing was imported: the database refused a row. " + firstLine(reason), null));
+ }
+
+ private static String firstLine(String text) {
+ return text == null ? "" : text.lines().findFirst().orElse("");
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/BatchingApplication.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/BatchingApplication.java
new file mode 100644
index 0000000..29f0898
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/BatchingApplication.java
@@ -0,0 +1,12 @@
+package com.amigoscode.batching;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class BatchingApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(BatchingApplication.class, args);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/ManagedEntities.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/ManagedEntities.java
new file mode 100644
index 0000000..107e080
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/ManagedEntities.java
@@ -0,0 +1,39 @@
+package com.amigoscode.batching.db;
+
+import java.util.Iterator;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.hibernate.Interceptor;
+
+/**
+ * Remembers the largest number of entities the persistence context held at any flush. Every
+ * entity Hibernate manages stays in memory, with a snapshot of its values for dirty checking,
+ * until the transaction ends or someone calls clear(). This makes that number visible.
+ *
+ * Switched on in application.properties with hibernate.session_factory.interceptor. Hibernate
+ * calls preFlush with every entity in the persistence context, right before each flush.
+ *
+ *
A teaching tool: do not ship a static, shared counter like this in a real application.
+ */
+public class ManagedEntities implements Interceptor {
+
+ private static final AtomicInteger PEAK = new AtomicInteger();
+
+ @Override
+ public void preFlush(Iterator entities) {
+ int count = 0;
+ while (entities.hasNext()) {
+ entities.next();
+ count++;
+ }
+ PEAK.accumulateAndGet(count, Math::max);
+ }
+
+ public static void reset() {
+ PEAK.set(0);
+ }
+
+ /** The most entities the persistence context held at a flush since the last reset(). */
+ public static int peak() {
+ return PEAK.get();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/Recording.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/Recording.java
new file mode 100644
index 0000000..b051e55
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/Recording.java
@@ -0,0 +1,85 @@
+package com.amigoscode.batching.db;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+/** Everything the application sent to Postgres between SqlRecorder.start() and stop(). */
+public record Recording(List calls, int commits, int rollbacks) {
+
+ /** One statement and everything that was sent with it. */
+ public record Shape(String sql, int roundTrips, int rows, Map batchSizes) {
+
+ /**
+ * "40 x 50" or "39 x 50, 1 x 17": how many batches of each size, biggest first. With more than
+ * three different sizes, "2,022 of 1 to 50 rows". Empty when nothing was batched.
+ */
+ public String describeBatches() {
+ if (batchSizes.size() > 3) {
+ int batches = batchSizes.values().stream().mapToInt(Integer::intValue).sum();
+ return String.format("%,d of %,d to %,d rows", batches,
+ batchSizes.keySet().stream().min(Integer::compare).orElseThrow(),
+ batchSizes.keySet().stream().max(Integer::compare).orElseThrow());
+ }
+ List parts = new ArrayList<>();
+ batchSizes.entrySet().stream()
+ .sorted(Map.Entry.comparingByKey().reversed())
+ .forEach(size -> parts.add(String.format("%,d x %,d", size.getValue(), size.getKey())));
+ return String.join(", ", parts);
+ }
+ }
+
+ public int roundTrips() {
+ return calls.size();
+ }
+
+ public int roundTrips(String sqlPrefix) {
+ return matching(sqlPrefix).size();
+ }
+
+ /** The number of rows (sets of values) sent with statements that start with the prefix. */
+ public int rows(String sqlPrefix) {
+ return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).sum();
+ }
+
+ /** The biggest single round trip for statements that start with the prefix, in rows. */
+ public int largestBatch(String sqlPrefix) {
+ return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).max().orElse(0);
+ }
+
+ public List matching(String sqlPrefix) {
+ return calls.stream().filter(call -> call.startsWith(sqlPrefix)).toList();
+ }
+
+ /** The calls grouped by statement, in the order each statement was first sent. */
+ public List shapes() {
+ Map> grouped = new LinkedHashMap<>();
+ for (SqlCall call : calls) {
+ grouped.computeIfAbsent(call.shape(), ignored -> new ArrayList<>()).add(call);
+ }
+ List shapes = new ArrayList<>();
+ grouped.forEach((sql, sameSql) -> {
+ Map batchSizes = new TreeMap<>();
+ sameSql.stream()
+ .filter(call -> call.kind() != SqlCall.Kind.SINGLE)
+ .forEach(call -> batchSizes.merge(call.rows(), 1, Integer::sum));
+ shapes.add(new Shape(sql, sameSql.size(), sameSql.stream().mapToInt(SqlCall::rows).sum(), batchSizes));
+ });
+ return shapes;
+ }
+
+ /** A few lines for a failure message: what was sent, grouped by statement. */
+ public String describe() {
+ StringBuilder text = new StringBuilder(String.format("%,d round trips:", roundTrips()));
+ for (Shape shape : shapes()) {
+ String sql = shape.sql().length() > 90 ? shape.sql().substring(0, 90) + "..." : shape.sql();
+ text.append(String.format("%n%,d x %s", shape.roundTrips(), sql));
+ if (!shape.batchSizes().isEmpty()) {
+ text.append(" [batches: ").append(shape.describeBatches()).append("]");
+ }
+ }
+ return text.toString();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlCall.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlCall.java
new file mode 100644
index 0000000..592da9c
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlCall.java
@@ -0,0 +1,29 @@
+package com.amigoscode.batching.db;
+
+import java.util.Locale;
+
+/**
+ * One round trip from the application to Postgres: one execute() of one statement, one
+ * executeBatch() of a JDBC batch, or one COPY. {@code rows} is how many sets of values it carried:
+ * 1 for a plain statement, the batch size for a batch, the number of rows for a COPY.
+ */
+public record SqlCall(String sql, Kind kind, int rows) {
+
+ public enum Kind {
+ /** execute(), executeQuery() or executeUpdate(): one statement, one set of values. */
+ SINGLE,
+ /** executeBatch(): the same statement with many sets of values, sent together. */
+ BATCH,
+ /** COPY ... FROM STDIN: one statement, the rows stream after it. */
+ COPY
+ }
+
+ /** The statement in lower case, on one line. */
+ public String shape() {
+ return sql.strip().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT);
+ }
+
+ public boolean startsWith(String prefix) {
+ return shape().startsWith(prefix.toLowerCase(Locale.ROOT));
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlRecorder.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlRecorder.java
new file mode 100644
index 0000000..a68fd9c
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlRecorder.java
@@ -0,0 +1,219 @@
+package com.amigoscode.batching.db;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+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;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import javax.sql.DataSource;
+import org.postgresql.PGConnection;
+import org.postgresql.copy.CopyIn;
+import org.postgresql.copy.CopyManager;
+import org.postgresql.core.BaseConnection;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.jdbc.datasource.DelegatingDataSource;
+
+/**
+ * Records every round trip the application makes to Postgres, whoever makes it: Hibernate, Spring
+ * Data, JdbcTemplate or a COPY. ./demo and the tests use it to answer "how many times did this
+ * import talk to the database, and how many rows did each trip carry?"
+ *
+ * SqlRecorder.start();
+ * ... run the import ...
+ * Recording recording = SqlRecorder.stop();
+ *
+ * It wraps the DataSource, so it sees exactly what reaches the JDBC driver: one execute() is one
+ * round trip, one executeBatch() is one round trip however many rows were added to the batch.
+ * (Hibernate's own statement counters count a batch differently, which is why they are not used.)
+ *
+ * A teaching tool: do not ship a static, shared recorder like this in a real application.
+ */
+public final class SqlRecorder {
+
+ private static final Object LOCK = new Object();
+ private static final Set EXECUTE = Set.of("execute", "executeQuery", "executeUpdate", "executeLargeUpdate");
+ private static final Set EXECUTE_BATCH = Set.of("executeBatch", "executeLargeBatch");
+
+ private static List calls;
+ private static int commits;
+ private static int rollbacks;
+
+ public static void start() {
+ synchronized (LOCK) {
+ calls = new ArrayList<>();
+ commits = 0;
+ rollbacks = 0;
+ }
+ }
+
+ /** Stops recording and returns what was sent since start(). */
+ public static Recording stop() {
+ synchronized (LOCK) {
+ Recording recording = new Recording(calls == null ? List.of() : List.copyOf(calls), commits, rollbacks);
+ calls = null;
+ return recording;
+ }
+ }
+
+ private static void record(String sql, SqlCall.Kind kind, int rows) {
+ synchronized (LOCK) {
+ if (calls != null) {
+ calls.add(new SqlCall(sql, kind, rows));
+ }
+ }
+ }
+
+ private static void recordEnd(boolean commit) {
+ synchronized (LOCK) {
+ if (calls != null) {
+ if (commit) {
+ commits++;
+ } else {
+ rollbacks++;
+ }
+ }
+ }
+ }
+
+ /** Wraps every DataSource bean of the application. */
+ @Configuration
+ static class Wiring {
+
+ @Bean
+ static BeanPostProcessor recordSqlOfEveryDataSource() {
+ return new BeanPostProcessor() {
+ @Override
+ public Object postProcessAfterInitialization(Object bean, String beanName) {
+ return bean instanceof DataSource dataSource && !(bean instanceof RecordingDataSource)
+ ? new RecordingDataSource(dataSource) : bean;
+ }
+ };
+ }
+ }
+
+ private static final class RecordingDataSource extends DelegatingDataSource {
+
+ RecordingDataSource(DataSource target) {
+ super(target);
+ }
+
+ @Override
+ public Connection getConnection() throws SQLException {
+ return watch(super.getConnection());
+ }
+
+ @Override
+ public Connection getConnection(String username, String password) throws SQLException {
+ return watch(super.getConnection(username, password));
+ }
+
+ private static Connection watch(Connection connection) {
+ return proxy(Connection.class, (proxy, method, args) -> {
+ String name = method.getName();
+ if (name.equals("unwrap") && args[0] == PGConnection.class) {
+ return watchCopy(connection.unwrap(PGConnection.class));
+ }
+ Object result = call(connection, method, args);
+ if (name.equals("commit")) {
+ recordEnd(true);
+ } else if (name.equals("rollback") && args == null) {
+ recordEnd(false);
+ } else if (name.equals("prepareStatement") && result instanceof PreparedStatement statement) {
+ return watch(statement, (String) args[0]);
+ } else if (name.equals("createStatement") && result instanceof Statement statement) {
+ return watch(statement);
+ }
+ return result;
+ });
+ }
+
+ private static PreparedStatement watch(PreparedStatement statement, String sql) {
+ int[] batched = {0};
+ return proxy(PreparedStatement.class, (proxy, method, args) -> {
+ String name = method.getName();
+ if (name.equals("addBatch") && args == null) {
+ batched[0]++;
+ } else if (name.equals("clearBatch")) {
+ batched[0] = 0;
+ } else if (EXECUTE_BATCH.contains(name)) {
+ record(sql, SqlCall.Kind.BATCH, batched[0]);
+ batched[0] = 0;
+ } else if (EXECUTE.contains(name) && args == null) {
+ record(sql, SqlCall.Kind.SINGLE, 1);
+ }
+ return call(statement, method, args);
+ });
+ }
+
+ /** A plain Statement: the SQL is passed to execute() itself. */
+ private static Statement watch(Statement statement) {
+ List batch = new ArrayList<>();
+ return proxy(Statement.class, (proxy, method, args) -> {
+ String name = method.getName();
+ if (name.equals("addBatch") && args != null) {
+ batch.add((String) args[0]);
+ } else if (EXECUTE_BATCH.contains(name) && !batch.isEmpty()) {
+ record(batch.getFirst(), SqlCall.Kind.BATCH, batch.size());
+ batch.clear();
+ } else if (EXECUTE.contains(name) && args != null && args[0] instanceof String sql) {
+ record(sql, SqlCall.Kind.SINGLE, 1);
+ }
+ return call(statement, method, args);
+ });
+ }
+
+ /** COPY does not go through a Statement at all: it is the driver's CopyManager. */
+ private static PGConnection watchCopy(PGConnection connection) {
+ return proxy(PGConnection.class, (proxy, method, args) -> {
+ if (method.getName().equals("getCopyAPI")) {
+ return new RecordingCopyManager((BaseConnection) connection);
+ }
+ return call(connection, method, args);
+ });
+ }
+
+ private static T proxy(Class type, InvocationHandler handler) {
+ return type.cast(Proxy.newProxyInstance(SqlRecorder.class.getClassLoader(), new Class>[] {type}, handler));
+ }
+
+ private static Object call(Object target, Method method, Object[] args) throws Throwable {
+ try {
+ return method.invoke(target, args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ }
+ }
+ }
+
+ /** Records a COPY when it ends, with the number of rows Postgres says it stored. */
+ private static final class RecordingCopyManager extends CopyManager {
+
+ RecordingCopyManager(BaseConnection connection) throws SQLException {
+ super(connection);
+ }
+
+ @Override
+ public CopyIn copyIn(String sql) throws SQLException {
+ CopyIn copy = super.copyIn(sql);
+ return RecordingDataSource.proxy(CopyIn.class, (proxy, method, args) -> {
+ Object result = RecordingDataSource.call(copy, method, args);
+ if (method.getName().equals("endCopy")) {
+ record(sql, SqlCall.Kind.COPY, (int) (long) (Long) result);
+ }
+ return result;
+ });
+ }
+
+ }
+
+ private SqlRecorder() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Db.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Db.java
new file mode 100644
index 0000000..dce5c1a
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Db.java
@@ -0,0 +1,52 @@
+package com.amigoscode.batching.demo;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */
+final class Db {
+
+ static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5455/batching");
+ static final String USER = env("DB_USER", "batching");
+ static final String PASSWORD = env("DB_PASSWORD", "batching");
+
+ private Db() {
+ }
+
+ /**
+ * A connection for the tools themselves. pg_stat_statements is told to ignore it, so the queries
+ * ./demo and ./inspect run to count things do not show up next to the application's statements.
+ */
+ static Connection connect() throws SQLException {
+ Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("set pg_stat_statements.track = 'none'");
+ } catch (SQLException notLoadedOrNotAllowed) {
+ // Without pg_stat_statements there is nothing to hide from.
+ }
+ return connection;
+ }
+
+ /** Returns false, after printing what to do, when Postgres is not reachable. */
+ static boolean isUp() {
+ try (Connection ignored = connect()) {
+ return true;
+ } catch (SQLException e) {
+ System.out.println();
+ System.out.println("Cannot reach Postgres at " + URL);
+ System.out.println("Start it first, from this folder:");
+ System.out.println();
+ System.out.println(" docker compose up -d");
+ System.out.println();
+ System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")");
+ return false;
+ }
+ }
+
+ private static String env(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isBlank() ? fallback : value;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Demo.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Demo.java
new file mode 100644
index 0000000..edd5b0e
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Demo.java
@@ -0,0 +1,441 @@
+package com.amigoscode.batching.demo;
+
+import com.amigoscode.batching.BatchingApplication;
+import com.amigoscode.batching.db.ManagedEntities;
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.db.SqlCall;
+import com.amigoscode.batching.db.SqlRecorder;
+import com.amigoscode.batching.price.PriceChange;
+import com.amigoscode.batching.product.Product;
+import com.amigoscode.batching.product.StockLevel;
+import jakarta.persistence.EntityManagerFactory;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import javax.sql.DataSource;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.generator.Generator;
+import org.hibernate.id.IdentityGenerator;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.postgresql.core.BaseConnection;
+import org.springframework.boot.Banner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.core.env.MapPropertySource;
+
+/**
+ * Starts the real application, sends it a generated CSV feed over HTTP, and prints how many round
+ * trips the import made to Postgres, what Postgres executed, and how many entities Hibernate held in
+ * memory. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags.
+ */
+public final class Demo {
+
+ private static final List STRATEGIES = List.of("one-by-one", "batched", "rewrite", "jdbc", "copy");
+ private static final int WIDTH = 74;
+
+ private record Options(String strategy, int rows, boolean stock, boolean prices, Boolean rewrite, boolean sql) {
+
+ /** The strategy the application knows: "rewrite" is "batched" with the driver setting on. */
+ String appStrategy() {
+ return strategy.equals("rewrite") ? "batched" : strategy;
+ }
+
+ boolean jpa() {
+ return prices || !(strategy.equals("jdbc") || strategy.equals("copy"));
+ }
+ }
+
+ /** One HTTP request and everything it caused. */
+ private record Phase(String title, int status, String body, Recording recording,
+ List executed, int peakEntities, long millis) {
+
+ int rowsWritten() {
+ return recording.calls().stream()
+ .filter(call -> call.startsWith("insert") || call.startsWith("update") || call.startsWith("copy"))
+ .mapToInt(SqlCall::rows)
+ .sum();
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options;
+ try {
+ options = parse(args);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ System.out.println();
+ printHelp();
+ return;
+ }
+ if (options == null) {
+ printHelp();
+ return;
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+
+ List springArgs = new ArrayList<>(List.of(
+ "--server.port=0",
+ "--logging.level.root=WARN",
+ "--logging.level.org.apache.catalina.core.ContainerBase=OFF",
+ "--spring.web.error.include-message=always"));
+ Boolean rewrite = options.strategy().equals("rewrite") ? Boolean.TRUE : options.rewrite();
+
+ SpringApplication app = new SpringApplication(BatchingApplication.class);
+ app.setBannerMode(Banner.Mode.OFF);
+ app.setLogStartupInfo(false);
+ if (rewrite != null) {
+ // An option on the URL beats a driver property, so the override goes on the URL itself.
+ app.addInitializers(context -> {
+ var environment = context.getEnvironment();
+ String url = withRewrite(environment.getProperty("spring.datasource.url", Db.URL), rewrite);
+ environment.getPropertySources().addFirst(new MapPropertySource("demo-rewrite",
+ java.util.Map.of("spring.datasource.url", url)));
+ });
+ }
+ try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new))) {
+ run(options, context);
+ }
+ }
+
+ private static void run(Options options, ConfigurableApplicationContext context) throws Exception {
+ String baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port");
+ HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+ int batchSize = context.getEnvironment().getProperty("spring.jpa.properties.hibernate.jdbc.batch_size", Integer.class, 0);
+
+ // A throwaway request first, so the import is not slowed down by start-up work.
+ http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding());
+
+ printHeader(options, context, batchSize);
+
+ List phases = new ArrayList<>();
+ try (Connection server = Db.connect()) {
+ boolean serverStats = ServerStats.available(server);
+ if (options.prices()) {
+ phases.add(send(http, server, serverStats, "PRICE HISTORY: " + number(options.rows()) + " price changes, saveAll()",
+ "POST", baseUrl + "/api/imports/prices", Feed.products(options.rows(), false)));
+ } else {
+ phases.add(send(http, server, serverStats, "IMPORT: " + number(options.rows()) + " new products"
+ + (options.stock() ? ", each with 3 stock levels" : ""),
+ "POST", baseUrl + "/api/imports/products?strategy=" + options.appStrategy(),
+ Feed.products(options.rows(), options.stock())));
+ if (options.stock() && phases.getFirst().status() == 200) {
+ phases.add(send(http, server, serverStats, "UPDATE: the next day's feed, a new price and new stock for every product",
+ "PUT", baseUrl + "/api/imports/products", Feed.nextDay(options.rows())));
+ }
+ }
+ if (!serverStats) {
+ System.out.println("(pg_stat_statements is not loaded in this Postgres, so the server side is not shown.");
+ System.out.println(" The compose.yaml of this project loads it: docker compose down, then docker compose up -d.)");
+ System.out.println();
+ }
+ }
+
+ for (Phase phase : phases) {
+ print(phase, options.sql());
+ }
+
+ long products;
+ long stockLevels;
+ long priceChanges;
+ try (Connection connection = Db.connect()) {
+ products = count(connection, "product");
+ stockLevels = count(connection, "stock_level");
+ priceChanges = count(connection, "price_change");
+ }
+ System.out.println("Rows in the database: " + number(products) + " products, " + number(stockLevels)
+ + " stock levels, " + number(priceChanges) + " price changes");
+ System.out.println();
+
+ printResults(options, phases, batchSize, options.prices() ? priceChanges : products);
+ }
+
+ private static long count(Connection connection, String table) throws java.sql.SQLException {
+ try (var statement = connection.createStatement(); var result = statement.executeQuery("select count(*) from " + table)) {
+ result.next();
+ return result.getLong(1);
+ }
+ }
+
+ private static Phase send(HttpClient http, Connection server, boolean serverStats, String title,
+ String method, String url, String csv) throws Exception {
+ HttpRequest request = HttpRequest.newBuilder(URI.create(url))
+ .header("Content-Type", "text/csv")
+ .method(method, HttpRequest.BodyPublishers.ofString(csv))
+ .build();
+ if (serverStats) {
+ ServerStats.reset(server);
+ }
+ ManagedEntities.reset();
+ SqlRecorder.start();
+ long started = System.nanoTime();
+ HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString());
+ long millis = (System.nanoTime() - started) / 1_000_000;
+ Recording recording = SqlRecorder.stop();
+ List executed = serverStats ? ServerStats.read(server) : List.of();
+ return new Phase(title, response.statusCode(), response.body(), recording, executed, ManagedEntities.peak(), millis);
+ }
+
+ /** The URL with reWriteBatchedInserts set to the given value, whatever it said before. */
+ private static String withRewrite(String url, boolean on) {
+ String clean = url.replaceAll("(?i)([?&])reWriteBatchedInserts=[^&]*&?", "$1").replaceAll("[?&]$", "");
+ return clean + (clean.contains("?") ? "&" : "?") + "reWriteBatchedInserts=" + on;
+ }
+
+ private static void printHeader(Options options, ConfigurableApplicationContext context, int batchSize) {
+ // Ask the driver itself: the option can come from the URL or from a driver property.
+ String rewrite = "?";
+ try (Connection connection = context.getBean(DataSource.class).getConnection()) {
+ rewrite = String.valueOf(connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled());
+ } catch (Exception ignored) {
+ // Not the Postgres driver: leave it as "?".
+ }
+ var environment = context.getEnvironment();
+ System.out.println();
+ System.out.println("Strategy: " + options.strategy() + (options.prices() ? " (ignored: --prices always uses saveAll)" : "")
+ + " | rows: " + number(options.rows()));
+ System.out.println("Settings: hibernate.jdbc.batch_size=" + (batchSize == 0 ? "(not set)" : batchSize)
+ + " | order_inserts=" + environment.getProperty("spring.jpa.properties.hibernate.order_inserts", "false")
+ + " | order_updates=" + environment.getProperty("spring.jpa.properties.hibernate.order_updates", "false")
+ + " | reWriteBatchedInserts=" + rewrite);
+ SessionFactoryImplementor hibernate = context.getBean(EntityManagerFactory.class).unwrap(SessionFactoryImplementor.class);
+ if (options.prices()) {
+ System.out.println("PriceChange ids: " + describe(generator(hibernate, PriceChange.class)));
+ } else if (options.jpa()) {
+ System.out.println("Product ids: " + describe(generator(hibernate, Product.class)));
+ if (options.stock()) {
+ System.out.println("StockLevel ids: " + describe(generator(hibernate, StockLevel.class)));
+ }
+ } else {
+ System.out.println("Product ids: the column default, nextval('product_seq') or the identity. No entities.");
+ }
+ System.out.println();
+ }
+
+ private static Generator generator(SessionFactoryImplementor hibernate, Class> entity) {
+ return hibernate.getMappingMetamodel().getEntityDescriptor(entity).getGenerator();
+ }
+
+ private static String describe(Generator generator) {
+ if (generator == null) {
+ return "assigned in Java: Hibernate generates nothing";
+ }
+ if (generator instanceof IdentityGenerator) {
+ return "IDENTITY. Postgres makes each id while it runs the INSERT";
+ }
+ if (generator instanceof SequenceStyleGenerator sequence) {
+ int allocation = sequence.getOptimizer().getIncrementSize();
+ return "SEQUENCE " + sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText()
+ + ", allocationSize " + allocation + " (" + sequence.getOptimizer().getClass().getSimpleName()
+ + ": " + (allocation == 1 ? "one nextval per row" : "one nextval per " + allocation + " ids") + ")";
+ }
+ String name = generator.getClass().getSimpleName();
+ if (name.equals("UuidGenerator")) {
+ return "UuidGenerator. Hibernate makes a UUID in memory when the entity is persisted";
+ }
+ return name.equals("Assigned") ? "assigned in Java: Hibernate generates nothing" : name;
+ }
+
+ private static void print(Phase phase, boolean sql) {
+ System.out.println(phase.title());
+ System.out.println("=".repeat(Math.min(phase.title().length(), WIDTH + 20)));
+ if (phase.status() != 200) {
+ System.out.println();
+ System.out.println(" HTTP " + phase.status() + ": " + phase.body());
+ System.out.println();
+ return;
+ }
+ Recording recording = phase.recording();
+ System.out.println();
+ System.out.println("What the application sent, counted at the JDBC driver (one execute or executeBatch = one round trip)");
+ List rows = new ArrayList<>();
+ rows.add(new String[] {"round trips", "rows", "batches (count x size)", "statement"});
+ for (Recording.Shape shape : recording.shapes()) {
+ rows.add(new String[] {number(shape.roundTrips()), number(shape.rows()), shape.describeBatches(), clip(shape.sql())});
+ }
+ Table.print(rows, 0, 1);
+ if (sql) {
+ System.out.println();
+ System.out.println("The first 25 round trips, in the order they were sent");
+ List calls = recording.calls();
+ for (int i = 0; i < Math.min(25, calls.size()); i++) {
+ SqlCall call = calls.get(i);
+ System.out.printf(" %4d %-6s %4d row%s %s%n", i + 1, call.kind().name().toLowerCase(Locale.ROOT),
+ call.rows(), call.rows() == 1 ? " " : "s", clip(call.shape()));
+ }
+ }
+ if (!phase.executed().isEmpty()) {
+ System.out.println();
+ System.out.println("What Postgres executed, counted by the server (pg_stat_statements)");
+ List executed = new ArrayList<>();
+ executed.add(new String[] {"executions", "rows", "rows each", "statement"});
+ for (ServerStats.Executed statement : phase.executed()) {
+ long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls();
+ executed.add(new String[] {number(statement.calls()), number(statement.rows()), number(each),
+ clip(ServerStats.shorten(statement.query()))});
+ }
+ Table.print(executed, 0, 1, 2);
+ }
+ System.out.println();
+ System.out.println("Round trips: " + number(recording.roundTrips()));
+ System.out.println("Commits: " + number(recording.commits()));
+ System.out.println("Peak entities held: " + number(phase.peakEntities())
+ + " (the most entities in Hibernate's persistence context at one flush)");
+ System.out.println("Time taken: " + number(phase.millis()) + " ms");
+ System.out.println();
+ }
+
+ private static void printResults(Options options, List phases, int batchSize, long rowsStored) {
+ List problems = new ArrayList<>();
+ for (Phase phase : phases) {
+ if (phase.status() != 200) {
+ problems.add("FAILED. " + phase.title().split(":")[0] + " returned HTTP " + phase.status() + ".");
+ continue;
+ }
+ Recording recording = phase.recording();
+ String what = phase.title().split(":")[0].toLowerCase(Locale.ROOT);
+ int selects = recording.roundTrips("select") - recording.roundTrips("select nextval");
+ if (options.prices() && selects > 0) {
+ problems.add(number(selects) + " SELECTS. saveAll() looked up every price change before inserting it.");
+ }
+ if (recording.commits() > 1) {
+ problems.add(number(recording.commits()) + " COMMITS. Every row was its own transaction.");
+ }
+ int rowsWritten = phase.rowsWritten();
+ if (recording.roundTrips() * 10L > rowsWritten) {
+ problems.add(number(recording.roundTrips()) + " ROUND TRIPS. The " + what + " wrote " + number(rowsWritten)
+ + " rows, " + perTrip(rowsWritten, recording.roundTrips()) + " per round trip.");
+ }
+ boolean importPhase = phase == phases.getFirst() && !options.prices() && options.jpa();
+ if (importPhase && batchSize > 0 && phase.peakEntities() > 4 * batchSize) {
+ problems.add(number(phase.peakEntities()) + " ENTITIES IN MEMORY. The persistence context held the whole "
+ + what + " until it ended.");
+ }
+ }
+ if (problems.isEmpty()) {
+ Phase first = phases.getFirst();
+ StringBuilder ok = new StringBuilder("RESULT: OK. " + number(rowsStored) + " rows in "
+ + roundTrips(first.recording().roundTrips()));
+ if (phases.size() > 1) {
+ ok.append(", updated in ").append(roundTrips(phases.get(1).recording().roundTrips()));
+ }
+ if (!options.prices() && options.jpa()) {
+ ok.append(", at most ").append(number(first.peakEntities())).append(" entities in memory");
+ }
+ System.out.println(ok.append('.'));
+ } else {
+ problems.forEach(problem -> System.out.println("RESULT: " + problem));
+ }
+ System.out.println();
+ }
+
+ private static String roundTrips(int count) {
+ return number(count) + (count == 1 ? " round trip" : " round trips");
+ }
+
+ private static String perTrip(int rows, int roundTrips) {
+ double average = roundTrips == 0 ? 0 : (double) rows / roundTrips;
+ return String.format(Locale.US, "%.1f", average);
+ }
+
+ private static String clip(String sql) {
+ return sql.length() > WIDTH ? sql.substring(0, WIDTH - 3) + "..." : sql;
+ }
+
+ static String number(long value) {
+ return String.format(Locale.US, "%,d", value);
+ }
+
+ private static Options parse(String[] args) {
+ String strategy = "batched";
+ int rows = 10_000;
+ boolean stock = false;
+ boolean prices = false;
+ Boolean rewrite = null;
+ boolean sql = false;
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ switch (arg) {
+ case "--help", "-h" -> {
+ return null;
+ }
+ case "--strategy" -> {
+ strategy = value(args, ++i, arg).toLowerCase(Locale.ROOT);
+ if (!STRATEGIES.contains(strategy)) {
+ throw new IllegalArgumentException("Unknown strategy '" + strategy + "'. Use one of: " + String.join(", ", STRATEGIES));
+ }
+ }
+ case "--rows" -> rows = number(value(args, ++i, arg), arg, 1, 100_000);
+ case "--stock" -> stock = true;
+ case "--prices" -> prices = true;
+ case "--rewrite" -> {
+ String value = value(args, ++i, arg).toLowerCase(Locale.ROOT);
+ if (!value.equals("on") && !value.equals("off")) {
+ throw new IllegalArgumentException("--rewrite must be on or off, got: " + value);
+ }
+ rewrite = value.equals("on");
+ }
+ case "--sql" -> sql = true;
+ default -> throw new IllegalArgumentException("Unknown option: " + arg);
+ }
+ }
+ if (stock && prices) {
+ throw new IllegalArgumentException("Use --stock or --prices, not both.");
+ }
+ if (stock && (strategy.equals("jdbc") || strategy.equals("copy"))) {
+ throw new IllegalArgumentException("--stock needs JPA: the " + strategy + " importer does not write stock levels (that is one of its trade-offs).");
+ }
+ return new Options(strategy, rows, stock, prices, rewrite, sql);
+ }
+
+ private static String value(String[] args, int index, String option) {
+ if (index >= args.length) {
+ throw new IllegalArgumentException(option + " needs a value");
+ }
+ return args[index];
+ }
+
+ private static int number(String value, String option, int min, int max) {
+ try {
+ int number = Integer.parseInt(value.replace(",", "").replace("_", ""));
+ if (number < min || number > max) {
+ throw new NumberFormatException();
+ }
+ return number;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(option + " must be a number from " + min + " to " + number(max) + ", got: " + value);
+ }
+ }
+
+ private static void printHelp() {
+ System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])");
+ System.out.println();
+ System.out.println(" --rows how many products the feed has (default: 10000)");
+ System.out.println(" --strategy how they reach the database (default: batched)");
+ System.out.println(" one-by-one JPA, one transaction per row (never changes: the reference)");
+ System.out.println(" batched JPA, one transaction, saveAll (Tasks 2 to 6 change this)");
+ System.out.println(" rewrite batched, with reWriteBatchedInserts=true for this run");
+ System.out.println(" jdbc JdbcTemplate.batchUpdate, no entities (Task 8)");
+ System.out.println(" copy Postgres COPY through the driver's CopyManager (Task 8)");
+ System.out.println(" --rewrite on|off force reWriteBatchedInserts for this run (default: application.properties)");
+ System.out.println(" --stock every product gets 3 stock levels, then a second feed updates them all");
+ System.out.println(" --prices write the price history instead: ids are UUIDs made in Java");
+ System.out.println(" --sql also list the first 25 round trips, in order");
+ System.out.println();
+ System.out.println("Examples:");
+ System.out.println(" ./demo");
+ System.out.println(" ./demo --strategy rewrite");
+ System.out.println(" ./demo --stock --rows 2000");
+ System.out.println(" ./demo --prices --rows 1000");
+ System.out.println(" ./demo --strategy copy --rows 100000");
+ }
+
+ private Demo() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Feed.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Feed.java
new file mode 100644
index 0000000..461ff10
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Feed.java
@@ -0,0 +1,55 @@
+package com.amigoscode.batching.demo;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+/** Builds the supplier's CSV feed. Same input every time, so two runs can be compared. */
+final class Feed {
+
+ static final List WAREHOUSES = List.of("GLA", "LON", "MAN");
+
+ private static final String[] COLOURS = {"Black", "White", "Red", "Blue", "Green", "Grey", "Yellow", "Navy"};
+ private static final String[] THINGS = {"mug", "kettle", "lamp", "chair", "desk", "pillow", "towel", "teapot", "vase", "clock"};
+
+ private Feed() {
+ }
+
+ /** The first feed: new products, optionally with stock in three warehouses. */
+ static String products(int rows, boolean withStock) {
+ return build(rows, withStock, 0);
+ }
+
+ /** The next day's feed: the same SKUs, every price up by 10% and different stock. */
+ static String nextDay(int rows) {
+ return build(rows, true, 1);
+ }
+
+ private static String build(int rows, boolean withStock, int day) {
+ StringBuilder csv = new StringBuilder(rows * 48);
+ csv.append("sku,name,price");
+ if (withStock) {
+ WAREHOUSES.forEach(warehouse -> csv.append(',').append(warehouse));
+ }
+ csv.append('\n');
+ for (int i = 1; i <= rows; i++) {
+ BigDecimal price = BigDecimal.valueOf(100 + (i * 37L) % 9900, 2);
+ if (day > 0) {
+ price = price.multiply(new BigDecimal("1.10")).setScale(2, java.math.RoundingMode.HALF_UP);
+ }
+ csv.append(sku(i)).append(',')
+ .append(COLOURS[i % COLOURS.length]).append(' ').append(THINGS[i % THINGS.length]).append(" no. ").append(i)
+ .append(',').append(price.toPlainString());
+ if (withStock) {
+ for (int w = 0; w < WAREHOUSES.size(); w++) {
+ csv.append(',').append((i * (w + 3) + day * 5) % 40);
+ }
+ }
+ csv.append('\n');
+ }
+ return csv.toString();
+ }
+
+ static String sku(int i) {
+ return String.format("SKU-%06d", i);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Inspect.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Inspect.java
new file mode 100644
index 0000000..69cd8fa
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Inspect.java
@@ -0,0 +1,149 @@
+package com.amigoscode.batching.demo;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Shows what the database holds after a ./demo run: how each table gets its ids, the sequences and
+ * how far they have moved, how far apart the stored ids are, and every statement Postgres executed
+ * for the last request of the demo (pg_stat_statements). Run it with ./inspect (or .\inspect on
+ * Windows) after ./demo.
+ */
+public final class Inspect {
+
+ private static final String ID_COLUMNS = """
+ select c.table_name as "table",
+ c.data_type as "type",
+ case when c.is_identity = 'YES' then 'IDENTITY: Postgres makes it while it runs the INSERT'
+ when c.column_default like 'nextval%' then 'DEFAULT ' || c.column_default
+ else 'none: the application must send it' end as "where the id comes from"
+ from information_schema.columns c
+ where c.table_schema = current_schema()
+ and c.table_name in ('product', 'stock_level', 'price_change')
+ and c.column_name = 'id'
+ order by c.table_name
+ """;
+
+ private static final String SEQUENCES = """
+ select sequencename as "sequence",
+ increment_by as "increment by",
+ coalesce(last_value::text, '(never used)') as "last value handed out"
+ from pg_sequences
+ where schemaname = current_schema()
+ order by sequencename
+ """;
+
+ private static final String IDS = """
+ with ids as (
+ select 'product' as t, null::text as uuid, id as n from product
+ union all select 'stock_level', null, id from stock_level
+ union all select 'price_change', id::text, null from price_change
+ ),
+ steps as (
+ select t, n - lag(n) over (partition by t order by n) as step from ids where n is not null
+ ),
+ common as (
+ select t, step, count(*) as times,
+ row_number() over (partition by t order by count(*) desc, step) as rank
+ from steps where step is not null group by t, step
+ )
+ select tables.t as "table",
+ to_char(count(i.t), 'FM999,999,990') as "rows",
+ coalesce(min(i.n)::text, min(i.uuid), '') as "lowest id",
+ coalesce(max(i.n)::text, max(i.uuid), '') as "highest id",
+ coalesce((select string_agg('+' || c.step || ' (' || to_char(c.times, 'FM999,999,990') || 'x)', ', ' order by c.rank)
+ from common c where c.t = tables.t and c.rank <= 3), '') as "most common gaps between neighbouring ids"
+ from (values ('product'), ('stock_level'), ('price_change')) as tables (t)
+ left join ids i on i.t = tables.t
+ group by tables.t
+ order by tables.t
+ """;
+
+ public static void main(String[] args) throws Exception {
+ if (args.length > 0) {
+ System.out.println("Usage: ./inspect (Windows: .\\inspect)");
+ System.out.println();
+ System.out.println("Run it after ./demo. It reads the database only, and changes nothing.");
+ return;
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+ try (Connection connection = Db.connect()) {
+ if (!tablesExist(connection)) {
+ System.out.println();
+ System.out.println("The tables do not exist yet. Run ./demo first.");
+ System.out.println();
+ return;
+ }
+ System.out.println();
+ System.out.println("WHERE EACH TABLE GETS ITS IDS (information_schema.columns)");
+ printTable(connection, ID_COLUMNS);
+ System.out.println();
+ System.out.println("SEQUENCES (pg_sequences)");
+ if (printTable(connection, SEQUENCES) == 0) {
+ System.out.println(" none.");
+ }
+ System.out.println();
+ System.out.println("THE ROWS AND THEIR IDS");
+ printTable(connection, IDS);
+ System.out.println();
+ System.out.println("WHAT POSTGRES EXECUTED FOR THE LAST REQUEST OF ./demo (pg_stat_statements)");
+ if (!ServerStats.available(connection)) {
+ System.out.println(" pg_stat_statements is not loaded in this Postgres. The compose.yaml of this project loads it:");
+ System.out.println(" docker compose down, then docker compose up -d.");
+ } else {
+ List rows = new ArrayList<>();
+ rows.add(new String[] {"executions", "rows", "rows each", "statement"});
+ for (ServerStats.Executed statement : ServerStats.read(connection)) {
+ long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls();
+ String query = ServerStats.shorten(statement.query());
+ rows.add(new String[] {Demo.number(statement.calls()), Demo.number(statement.rows()), Demo.number(each),
+ query.length() > 90 ? query.substring(0, 87) + "..." : query});
+ }
+ Table.print(rows, 0, 1, 2);
+ }
+ System.out.println();
+ }
+ }
+
+ private static boolean tablesExist(Connection connection) throws SQLException {
+ try (Statement statement = connection.createStatement();
+ ResultSet result = statement.executeQuery("select to_regclass('product') is not null")) {
+ result.next();
+ return result.getBoolean(1);
+ }
+ }
+
+ /** Prints a query result as a plain text table and returns the number of rows. */
+ private static int printTable(Connection connection, String sql) throws SQLException {
+ List rows = new ArrayList<>();
+ try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) {
+ int columns = result.getMetaData().getColumnCount();
+ String[] header = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ header[c] = result.getMetaData().getColumnLabel(c + 1);
+ }
+ rows.add(header);
+ while (result.next()) {
+ String[] row = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ String value = result.getString(c + 1);
+ row[c] = value == null ? "" : value;
+ }
+ rows.add(row);
+ }
+ }
+ if (rows.size() > 1) {
+ Table.print(rows);
+ }
+ return rows.size() - 1;
+ }
+
+ private Inspect() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/ServerStats.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/ServerStats.java
new file mode 100644
index 0000000..e5ed34b
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/ServerStats.java
@@ -0,0 +1,72 @@
+package com.amigoscode.batching.demo;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Reads pg_stat_statements: what Postgres itself executed, counted on the server. The application
+ * side (SqlRecorder) counts round trips; this side counts statements. They are not the same number
+ * once the driver starts rewriting batches.
+ */
+final class ServerStats {
+
+ /** One statement as Postgres normalised it ($1, $2 for the values), how often it ran, and the rows. */
+ record Executed(String query, long calls, long rows) {
+ }
+
+ private static final String READ = """
+ select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows
+ from pg_stat_statements
+ where dbid = (select oid from pg_database where datname = current_database())
+ and query !~* 'pg_stat_statements|pg_catalog|information_schema|pg_sequences|pg_class|pg_attribute'
+ and query ~* '^\\s*(insert|update|delete|select|copy|with)'
+ order by calls desc, query
+ """;
+
+ private ServerStats() {
+ }
+
+ /** False when the extension is not loaded (compose.yaml loads it; another Postgres may not). */
+ static boolean available(Connection connection) {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("select 1 from pg_stat_statements limit 1");
+ return true;
+ } catch (SQLException e) {
+ return false;
+ }
+ }
+
+ static void reset(Connection connection) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("select pg_stat_statements_reset()");
+ }
+ }
+
+ static List read(Connection connection) throws SQLException {
+ List executed = new ArrayList<>();
+ try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(READ)) {
+ while (result.next()) {
+ executed.add(new Executed(result.getString(1), result.getLong(2), result.getLong(3)));
+ }
+ }
+ return executed;
+ }
+
+ /** A multi-row INSERT has one "($1,$2,$3)" per row: keeps the first one and replaces the rest with "...". */
+ static String shorten(String query) {
+ int values = query.toLowerCase().indexOf(" values (");
+ if (values < 0) {
+ return query;
+ }
+ int firstEnd = query.indexOf(')', values);
+ int rest = query.indexOf("),(", values);
+ if (rest < 0) {
+ rest = query.indexOf("), (", values);
+ }
+ return rest < 0 || rest != firstEnd ? query : query.substring(0, firstEnd + 1) + ",...";
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Table.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Table.java
new file mode 100644
index 0000000..15e2cda
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Table.java
@@ -0,0 +1,41 @@
+package com.amigoscode.batching.demo;
+
+import java.util.Arrays;
+import java.util.List;
+
+/** Prints rows as a plain text table. The first row is the header. */
+final class Table {
+
+ private Table() {
+ }
+
+ /** {@code rightAligned} are the column numbers to align to the right (the numbers). */
+ static void print(List rows, int... rightAligned) {
+ if (rows.size() == 1) {
+ System.out.println(" (nothing)");
+ return;
+ }
+ int[] widths = new int[rows.getFirst().length];
+ for (String[] row : rows) {
+ for (int c = 0; c < row.length; c++) {
+ widths[c] = Math.max(widths[c], row[c].length());
+ }
+ }
+ for (int r = 0; r < rows.size(); r++) {
+ StringBuilder line = new StringBuilder(" ");
+ for (int c = 0; c < widths.length; c++) {
+ int column = c;
+ boolean right = r > 0 && Arrays.stream(rightAligned).anyMatch(n -> n == column);
+ line.append(String.format("%" + (right ? "" : "-") + widths[c] + "s", rows.get(r)[c])).append(" ");
+ }
+ System.out.println(line.toString().stripTrailing());
+ if (r == 0) {
+ StringBuilder rule = new StringBuilder(" ");
+ for (int width : widths) {
+ rule.append("-".repeat(width)).append(" ");
+ }
+ System.out.println(rule.toString().stripTrailing());
+ }
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/BadCsvException.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/BadCsvException.java
new file mode 100644
index 0000000..c75efc6
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/BadCsvException.java
@@ -0,0 +1,16 @@
+package com.amigoscode.batching.imports;
+
+/** A line of the uploaded CSV that cannot be read. Becomes a 400 with the line number. */
+public class BadCsvException extends RuntimeException {
+
+ private final int line;
+
+ public BadCsvException(int line, String problem) {
+ super("Line " + line + ": " + problem);
+ this.line = line;
+ }
+
+ public int line() {
+ return line;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportController.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportController.java
new file mode 100644
index 0000000..c4c3599
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportController.java
@@ -0,0 +1,47 @@
+package com.amigoscode.batching.imports;
+
+import java.io.Reader;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * The supplier's feed arrives as CSV in the request body (see ProductCsv for the format).
+ *
+ *
+ * POST /api/imports/products?strategy=batched new products: one-by-one | batched | jdbc | copy
+ * PUT /api/imports/products same SKUs again: new prices and new stock
+ * POST /api/imports/prices one price change per row, into the price history
+ *
+ */
+@RestController
+@RequestMapping("/api/imports")
+public class ImportController {
+
+ public record ImportResponse(String strategy, long rows) {
+ }
+
+ private final ImportService imports;
+
+ public ImportController(ImportService imports) {
+ this.imports = imports;
+ }
+
+ @PostMapping(path = "/products", consumes = "text/csv")
+ public ImportResponse importProducts(@RequestParam(defaultValue = "batched") String strategy, Reader body) {
+ ImportStrategy chosen = ImportStrategy.from(strategy);
+ return new ImportResponse(chosen.label(), imports.importProducts(chosen, ProductCsv.read(body)));
+ }
+
+ @PutMapping(path = "/products", consumes = "text/csv")
+ public ImportResponse updateProducts(Reader body) {
+ return new ImportResponse("update", imports.updateProducts(ProductCsv.read(body).toList()));
+ }
+
+ @PostMapping(path = "/prices", consumes = "text/csv")
+ public ImportResponse recordPrices(Reader body) {
+ return new ImportResponse("price-history", imports.recordPrices(ProductCsv.read(body).toList()));
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportService.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportService.java
new file mode 100644
index 0000000..a3276d9
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportService.java
@@ -0,0 +1,40 @@
+package com.amigoscode.batching.imports;
+
+import com.amigoscode.batching.price.PriceHistory;
+import com.amigoscode.batching.product.JdbcProductImporter;
+import com.amigoscode.batching.product.ProductImporter;
+import com.amigoscode.batching.product.ProductRow;
+import java.util.List;
+import org.springframework.stereotype.Service;
+
+/** Picks the importer. Deliberately not transactional: each importer decides its own transactions. */
+@Service
+public class ImportService {
+
+ private final ProductImporter jpa;
+ private final JdbcProductImporter jdbc;
+ private final PriceHistory priceHistory;
+
+ public ImportService(ProductImporter jpa, JdbcProductImporter jdbc, PriceHistory priceHistory) {
+ this.jpa = jpa;
+ this.jdbc = jdbc;
+ this.priceHistory = priceHistory;
+ }
+
+ public long importProducts(ImportStrategy strategy, Iterable rows) {
+ return switch (strategy) {
+ case ONE_BY_ONE -> jpa.importOneByOne(rows);
+ case BATCHED -> jpa.importBatched(rows);
+ case JDBC -> jdbc.batchInsert(rows);
+ case COPY -> jdbc.copy(rows);
+ };
+ }
+
+ public long updateProducts(List rows) {
+ return jpa.updateAll(rows);
+ }
+
+ public long recordPrices(List rows) {
+ return priceHistory.record(rows);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java
new file mode 100644
index 0000000..905bca8
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java
@@ -0,0 +1,40 @@
+package com.amigoscode.batching.imports;
+
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.stream.Collectors;
+
+/** How the rows of an import reach the database. Chosen per request with ?strategy=. */
+public enum ImportStrategy {
+
+ /** JPA, one transaction per row. Stays as it is, so you can always compare against it. */
+ ONE_BY_ONE,
+ /** JPA, the whole file in one transaction with saveAll. Tasks 2 to 6. */
+ BATCHED,
+ /** JdbcTemplate.batchUpdate, no entities. Task 8. */
+ JDBC,
+ /** Postgres COPY through the driver's CopyManager. Task 8. */
+ COPY;
+
+ public String label() {
+ return name().toLowerCase(Locale.ROOT).replace('_', '-');
+ }
+
+ public static ImportStrategy from(String value) {
+ return Arrays.stream(values())
+ .filter(strategy -> strategy.label().equals(value == null ? "" : value.trim().toLowerCase(Locale.ROOT)))
+ .findFirst()
+ .orElseThrow(() -> new UnknownStrategyException(value));
+ }
+
+ public static String labels() {
+ return Arrays.stream(values()).map(ImportStrategy::label).collect(Collectors.joining(", "));
+ }
+
+ public static class UnknownStrategyException extends RuntimeException {
+
+ public UnknownStrategyException(String value) {
+ super("Unknown strategy '" + value + "'. Use one of: " + labels());
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ProductCsv.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ProductCsv.java
new file mode 100644
index 0000000..21dbd43
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ProductCsv.java
@@ -0,0 +1,184 @@
+package com.amigoscode.batching.imports;
+
+import com.amigoscode.batching.product.ProductRow;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.UncheckedIOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+/**
+ * Reads a product feed one row at a time, so a big file is never held in memory as a whole.
+ *
+ *
+ * sku,name,price,LON,MAN
+ * SKU-00001,"Mug, large",7.50,12,3
+ *
+ *
+ * The first three columns are fixed. Every column after them is a warehouse, and its value is the
+ * stock in that warehouse. Fields may be quoted with double quotes, and a quote inside a quoted
+ * field is written twice ("").
+ */
+public final class ProductCsv implements Iterable {
+
+ private final Reader reader;
+ private boolean used;
+
+ private ProductCsv(Reader reader) {
+ this.reader = reader;
+ }
+
+ public static ProductCsv read(Reader reader) {
+ return new ProductCsv(reader);
+ }
+
+ /** Can be iterated once: the rows are read from the reader as you go. */
+ @Override
+ public Iterator iterator() {
+ if (used) {
+ throw new IllegalStateException("A ProductCsv can only be read once");
+ }
+ used = true;
+ Records records = new Records(reader);
+ List header = records.next();
+ if (header == null || header.size() < 3
+ || !header.get(0).equals("sku") || !header.get(1).equals("name") || !header.get(2).equals("price")) {
+ throw new BadCsvException(1, "the first line must be the header sku,name,price followed by optional warehouse codes");
+ }
+ List warehouses = List.copyOf(header.subList(3, header.size()));
+ return new Iterator<>() {
+
+ private List next = records.next();
+
+ @Override
+ public boolean hasNext() {
+ return next != null;
+ }
+
+ @Override
+ public ProductRow next() {
+ if (next == null) {
+ throw new NoSuchElementException();
+ }
+ ProductRow row = toRow(next, records.line(), header.size(), warehouses);
+ next = records.next();
+ return row;
+ }
+ };
+ }
+
+ /** Reads the whole file into a list. Fine for a small file, or when you need every row at once. */
+ public List toList() {
+ List rows = new ArrayList<>();
+ forEach(rows::add);
+ return rows;
+ }
+
+ private static ProductRow toRow(List fields, int line, int columns, List warehouses) {
+ if (fields.size() != columns) {
+ throw new BadCsvException(line, "expected " + columns + " fields, found " + fields.size());
+ }
+ if (fields.get(0).isBlank()) {
+ throw new BadCsvException(line, "sku is empty");
+ }
+ BigDecimal price;
+ try {
+ price = new BigDecimal(fields.get(2).trim());
+ } catch (NumberFormatException e) {
+ throw new BadCsvException(line, "price is not a number: " + fields.get(2));
+ }
+ Map stock = new LinkedHashMap<>();
+ for (int i = 0; i < warehouses.size(); i++) {
+ String value = fields.get(3 + i).trim();
+ try {
+ stock.put(warehouses.get(i), Integer.parseInt(value));
+ } catch (NumberFormatException e) {
+ throw new BadCsvException(line, "stock for " + warehouses.get(i) + " is not a whole number: " + value);
+ }
+ }
+ return new ProductRow(fields.get(0).trim(), fields.get(1), price, stock);
+ }
+
+ /** Splits the text into records of fields. Knows about quotes, nothing else. */
+ private static final class Records {
+
+ private final Reader reader;
+ private int linesRead;
+ private int recordStart;
+
+ Records(Reader reader) {
+ this.reader = reader;
+ }
+
+ /** The line the last record started on. */
+ int line() {
+ return recordStart;
+ }
+
+ /** The next record, or null at the end of the file. Empty lines are skipped. */
+ List next() {
+ int c = read();
+ while (c == '\n' || c == '\r') {
+ if (c == '\n') {
+ linesRead++;
+ }
+ c = read();
+ }
+ if (c == -1) {
+ return null;
+ }
+ recordStart = linesRead + 1;
+ List fields = new ArrayList<>();
+ StringBuilder field = new StringBuilder();
+ boolean quoted = false;
+ while (true) {
+ if (quoted) {
+ if (c == -1) {
+ throw new BadCsvException(recordStart, "a quoted field is never closed");
+ }
+ if (c == '"') {
+ int after = read();
+ if (after != '"') {
+ quoted = false;
+ c = after;
+ continue;
+ }
+ field.append('"');
+ } else {
+ if (c == '\n') {
+ linesRead++;
+ }
+ field.append((char) c);
+ }
+ } else if (c == '"' && field.isEmpty()) {
+ quoted = true;
+ } else if (c == ',') {
+ fields.add(field.toString());
+ field.setLength(0);
+ } else if (c == '\n' || c == -1) {
+ if (c == '\n') {
+ linesRead++;
+ }
+ fields.add(field.toString());
+ return fields;
+ } else if (c != '\r') {
+ field.append((char) c);
+ }
+ c = read();
+ }
+ }
+
+ private int read() {
+ try {
+ return reader.read();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChange.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChange.java
new file mode 100644
index 0000000..ee06ea6
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChange.java
@@ -0,0 +1,59 @@
+package com.amigoscode.batching.price;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.UUID;
+
+/**
+ * One line of the price history. The id is a UUID made in Java, so the database is not asked for
+ * one.
+ *
+ * TODO Task 7: saving 1,000 of these sends 1,000 SELECTs nobody wrote. Find out who sends them
+ * and why, and make save() INSERT a new price change straight away.
+ */
+@Entity
+@Table(name = "price_change")
+public class PriceChange {
+
+ @Id
+ private UUID id;
+
+ private String sku;
+
+ private BigDecimal price;
+
+ private Instant changedAt;
+
+ protected PriceChange() {
+ }
+
+ public PriceChange(String sku, BigDecimal price, Instant changedAt) {
+ this.id = UUID.randomUUID();
+ this.sku = sku;
+ this.price = price;
+ this.changedAt = changedAt;
+ }
+
+ public UUID getId() {
+ return id;
+ }
+
+ public String getSku() {
+ return sku;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public void setPrice(BigDecimal price) {
+ this.price = price;
+ }
+
+ public Instant getChangedAt() {
+ return changedAt;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java
new file mode 100644
index 0000000..aa3701b
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java
@@ -0,0 +1,7 @@
+package com.amigoscode.batching.price;
+
+import java.util.UUID;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface PriceChangeRepository extends JpaRepository {
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceHistory.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceHistory.java
new file mode 100644
index 0000000..c979835
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceHistory.java
@@ -0,0 +1,28 @@
+package com.amigoscode.batching.price;
+
+import com.amigoscode.batching.product.ProductRow;
+import java.time.Instant;
+import java.util.List;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/** Writes one price change per row of the feed, all in one transaction. */
+@Service
+public class PriceHistory {
+
+ private final PriceChangeRepository priceChanges;
+
+ public PriceHistory(PriceChangeRepository priceChanges) {
+ this.priceChanges = priceChanges;
+ }
+
+ @Transactional
+ public int record(List rows) {
+ Instant now = Instant.now();
+ List changes = rows.stream()
+ .map(row -> new PriceChange(row.sku(), row.price(), now))
+ .toList();
+ priceChanges.saveAll(changes);
+ return changes.size();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java
new file mode 100644
index 0000000..345374e
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java
@@ -0,0 +1,79 @@
+package com.amigoscode.batching.product;
+
+import java.nio.charset.StandardCharsets;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+import org.postgresql.PGConnection;
+import org.postgresql.copy.CopyIn;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.jdbc.core.ConnectionCallback;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Imports products without JPA: no entities, no persistence context, no cascades. The id comes from
+ * the column's default, and stock levels are not imported at all.
+ */
+@Service
+public class JdbcProductImporter {
+
+ private static final String INSERT = "insert into product (sku, name, price) values (?, ?, ?)";
+ private static final String COPY = "copy product (sku, name, price) from stdin with (format csv)";
+
+ private final JdbcTemplate jdbc;
+ private final int batchSize;
+
+ public JdbcProductImporter(JdbcTemplate jdbc,
+ @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) {
+ this.jdbc = jdbc;
+ this.batchSize = batchSize;
+ }
+
+ /**
+ * TODO Task 8: no Hibernate here, and still one round trip per row. Send the rows in batches of
+ * batchSize, in one transaction.
+ */
+ @Transactional
+ public int batchInsert(Iterable rows) {
+ int count = 0;
+ for (ProductRow row : rows) {
+ jdbc.update(INSERT, row.sku(), row.name(), row.price());
+ count++;
+ }
+ return count;
+ }
+
+ /**
+ * COPY: one statement, and the rows stream after it as CSV text.
+ *
+ * TODO Task 8: fine for the demo's product names. Try a name with a comma in it.
+ */
+ @Transactional
+ public long copy(Iterable rows) {
+ return jdbc.execute((ConnectionCallback) connection -> {
+ CopyIn copy = connection.unwrap(PGConnection.class).getCopyAPI().copyIn(COPY);
+ try {
+ for (ProductRow row : rows) {
+ byte[] line = (row.sku() + "," + row.name() + "," + row.price().toPlainString() + "\n")
+ .getBytes(StandardCharsets.UTF_8);
+ copy.writeToCopy(line, 0, line.length);
+ }
+ return copy.endCopy();
+ } finally {
+ if (copy.isActive()) {
+ cancel(copy);
+ }
+ }
+ });
+ }
+
+ private static void cancel(CopyIn copy) {
+ try {
+ copy.cancelCopy();
+ } catch (SQLException ignored) {
+ // The COPY already failed. That first error is the one worth reporting.
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/Product.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/Product.java
new file mode 100644
index 0000000..3d9a749
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/Product.java
@@ -0,0 +1,91 @@
+package com.amigoscode.batching.product;
+
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+@Entity
+@Table(name = "product")
+public class Product {
+
+ /**
+ * Postgres makes the id while it runs the INSERT (the column is GENERATED BY DEFAULT AS IDENTITY,
+ * see schema.sql).
+ *
+ * TODO Task 2: application.properties already asks Hibernate for batches of 50, and nothing is
+ * batched. Find out why, then let the ids come from a sequence instead.
+ */
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ private String sku;
+
+ private String name;
+
+ private BigDecimal price;
+
+ @OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
+ private List stockLevels = new ArrayList<>();
+
+ protected Product() {
+ }
+
+ public Product(String sku, String name, BigDecimal price) {
+ this.sku = sku;
+ this.name = name;
+ this.price = price;
+ }
+
+ /** A new product with one stock level per warehouse in the row. */
+ public static Product from(ProductRow row) {
+ Product product = new Product(row.sku(), row.name(), row.price());
+ new TreeMap<>(row.stock()).forEach(product::addStock);
+ return product;
+ }
+
+ public void addStock(String warehouse, int quantity) {
+ stockLevels.add(new StockLevel(this, warehouse, quantity));
+ }
+
+ /** Takes the new price and the new stock per warehouse from the feed. */
+ public void update(ProductRow row) {
+ this.price = row.price();
+ Map stock = row.stock();
+ for (StockLevel level : stockLevels) {
+ Integer quantity = stock.get(level.getWarehouse());
+ if (quantity != null) {
+ level.setQuantity(quantity);
+ }
+ }
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getSku() {
+ return sku;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public List getStockLevels() {
+ return stockLevels;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductImporter.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductImporter.java
new file mode 100644
index 0000000..06da2af
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductImporter.java
@@ -0,0 +1,78 @@
+package com.amigoscode.batching.product;
+
+import jakarta.persistence.EntityManager;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/** Imports the supplier's feed with JPA. */
+@Service
+public class ProductImporter {
+
+ /** Postgres accepts at most 32,767 bind parameters in one statement, so a long IN list is split. */
+ private static final int SKUS_PER_QUERY = 1_000;
+
+ private final ProductRepository products;
+ private final EntityManager entityManager;
+ private final int batchSize;
+
+ public ProductImporter(ProductRepository products, EntityManager entityManager,
+ @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) {
+ this.products = products;
+ this.entityManager = entityManager;
+ this.batchSize = batchSize;
+ }
+
+ /**
+ * The reference. Not @Transactional, so every save() is its own transaction: one INSERT and one
+ * COMMIT per row. Leave this one as it is, so you can always compare against it.
+ */
+ public int importOneByOne(Iterable rows) {
+ int count = 0;
+ for (ProductRow row : rows) {
+ products.save(Product.from(row));
+ count++;
+ }
+ return count;
+ }
+
+ /**
+ * The whole file in one transaction, with saveAll.
+ *
+ * TODO Task 6: every product saved here stays in the persistence context until the transaction
+ * ends. Keep at most batchSize of them in memory at any time, without breaking the batches and
+ * without splitting the import into several transactions.
+ */
+ @Transactional
+ public int importBatched(Iterable rows) {
+ List all = new ArrayList<>();
+ for (ProductRow row : rows) {
+ all.add(Product.from(row));
+ }
+ products.saveAll(all);
+ return all.size();
+ }
+
+ /** The next day's feed: same SKUs, new prices and new stock. Returns how many products changed. */
+ @Transactional
+ public int updateAll(List rows) {
+ Map bySku = new LinkedHashMap<>();
+ rows.forEach(row -> bySku.put(row.sku(), row));
+ List skus = new ArrayList<>(bySku.keySet());
+ int updated = 0;
+ for (int from = 0; from < skus.size(); from += SKUS_PER_QUERY) {
+ List page = skus.subList(from, Math.min(from + SKUS_PER_QUERY, skus.size()));
+ for (Product product : products.findWithStockLevelsBySkuIn(page)) {
+ product.update(bySku.get(product.getSku()));
+ updated++;
+ }
+ }
+ // No save() needed: every product is managed, so Hibernate sends an UPDATE for each one it
+ // finds changed when the transaction commits.
+ return updated;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRepository.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRepository.java
new file mode 100644
index 0000000..abb1615
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRepository.java
@@ -0,0 +1,13 @@
+package com.amigoscode.batching.product;
+
+import java.util.Collection;
+import java.util.List;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+public interface ProductRepository extends JpaRepository {
+
+ @Query("select distinct p from Product p left join fetch p.stockLevels where p.sku in :skus")
+ List findWithStockLevelsBySkuIn(@Param("skus") Collection skus);
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRow.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRow.java
new file mode 100644
index 0000000..b936374
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRow.java
@@ -0,0 +1,16 @@
+package com.amigoscode.batching.product;
+
+import java.math.BigDecimal;
+import java.util.Map;
+
+/** One line of the supplier's feed. {@code stock} is the quantity per warehouse code, and may be empty. */
+public record ProductRow(String sku, String name, BigDecimal price, Map stock) {
+
+ public ProductRow {
+ stock = Map.copyOf(stock);
+ }
+
+ public ProductRow(String sku, String name, BigDecimal price) {
+ this(sku, name, price, Map.of());
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/StockLevel.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/StockLevel.java
new file mode 100644
index 0000000..d28f423
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/StockLevel.java
@@ -0,0 +1,54 @@
+package com.amigoscode.batching.product;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+
+/** How many of a product one warehouse holds. Saved together with its product (cascade). */
+@Entity
+@Table(name = "stock_level")
+public class StockLevel {
+
+ // TODO Task 5: same problem as Product.
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @ManyToOne(fetch = FetchType.LAZY, optional = false)
+ @JoinColumn(name = "product_id")
+ private Product product;
+
+ private String warehouse;
+
+ private int quantity;
+
+ protected StockLevel() {
+ }
+
+ StockLevel(Product product, String warehouse, int quantity) {
+ this.product = product;
+ this.warehouse = warehouse;
+ this.quantity = quantity;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getWarehouse() {
+ return warehouse;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ void setQuantity(int quantity) {
+ this.quantity = quantity;
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/application.properties b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/application.properties
new file mode 100644
index 0000000..f7a87d7
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/application.properties
@@ -0,0 +1,21 @@
+spring.application.name=batch-writes
+
+# Postgres from compose.yaml. Port 5455 so it does not clash with a Postgres you already run.
+spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5455/batching}
+spring.datasource.username=${DB_USER:batching}
+spring.datasource.password=${DB_PASSWORD:batching}
+
+spring.jpa.hibernate.ddl-auto=none
+spring.jpa.open-in-view=false
+
+# schema.sql drops and creates the tables on every start, so every run begins empty.
+spring.sql.init.mode=always
+
+# Send INSERTs and UPDATEs in JDBC batches of 50 statements. (Or so it says: see Task 1.)
+spring.jpa.properties.hibernate.jdbc.batch_size=50
+
+# Counts the entities in the persistence context at every flush. ./demo and the tests read it.
+spring.jpa.properties.hibernate.session_factory.interceptor=com.amigoscode.batching.db.ManagedEntities
+
+# Uncomment to see every SQL statement (or run ./demo --sql).
+# logging.level.org.hibernate.SQL=DEBUG
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/schema.sql b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/schema.sql
new file mode 100644
index 0000000..8df2b32
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/schema.sql
@@ -0,0 +1,33 @@
+-- Runs on every start, so every run begins with empty tables.
+
+-- Counts every statement Postgres executes. ./demo and ./inspect read it. It needs
+-- shared_preload_libraries=pg_stat_statements, which compose.yaml sets.
+create extension if not exists pg_stat_statements;
+
+drop table if exists stock_level, product, price_change;
+drop sequence if exists product_seq, stock_level_seq;
+
+-- Postgres makes each id while it runs the INSERT.
+create table product (
+ id bigint primary key generated by default as identity,
+ sku text not null unique,
+ name text not null,
+ price numeric(10,2) not null check (price >= 0)
+);
+
+create table stock_level (
+ id bigint primary key generated by default as identity,
+ product_id bigint not null references product (id),
+ warehouse text not null,
+ quantity int not null check (quantity >= 0)
+);
+
+create index stock_level_product_id on stock_level (product_id);
+
+-- The id is a UUID made in Java (see PriceChange).
+create table price_change (
+ id uuid primary key,
+ sku text not null,
+ price numeric(10,2) not null,
+ changed_at timestamptz not null
+);
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/Check.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/Check.java
new file mode 100644
index 0000000..50781ec
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/Check.java
@@ -0,0 +1,116 @@
+package com.amigoscode.batching;
+
+import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.discovery.ClassNameFilter;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.TagFilter;
+import org.junit.platform.launcher.TestExecutionListener;
+import org.junit.platform.launcher.TestIdentifier;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+
+/**
+ * Runs the tests that belong to one task and prints one line per acceptance criterion.
+ * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2
+ * (./mvnw verify runs the same tests the usual Maven way.)
+ */
+public final class Check {
+
+ /** Tasks that have tests. Task 3 is an inspection task: you answer questions, no code. */
+ private static final Map TASKS = new LinkedHashMap<>();
+
+ static {
+ TASKS.put("baseline", "Baseline: the CSV format and the HTTP contract (passes from the start, must stay green)");
+ TASKS.put("1", "Task 1: See 10,000 round trips");
+ TASKS.put("2", "Task 2: Let Hibernate batch: SEQUENCE instead of IDENTITY");
+ TASKS.put("4", "Task 4: Multi-row INSERTs: reWriteBatchedInserts");
+ TASKS.put("5", "Task 5: Parents and children: order_inserts and order_updates");
+ TASKS.put("6", "Task 6: Flat memory: flush and clear");
+ TASKS.put("7", "Task 7: Ids made in Java: no SELECT before every INSERT");
+ TASKS.put("8", "Task 8: Leave JPA: JdbcTemplate and COPY");
+ }
+
+ public static void main(String[] args) {
+ if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) {
+ System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything.");
+ System.exit(2);
+ }
+ if (args.length == 1 && !TASKS.containsKey(args[0])) {
+ System.out.println();
+ System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:");
+ System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions.");
+ System.out.println();
+ return;
+ }
+
+ boolean allGreen = true;
+ Launcher launcher = LauncherFactory.create();
+ for (Map.Entry task : TASKS.entrySet()) {
+ if (args.length == 1 && !task.getKey().equals(args[0])) {
+ continue;
+ }
+ String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey();
+ LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectPackage(Check.class.getPackageName()))
+ .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag))
+ .build();
+ System.out.println();
+ System.out.println(task.getValue());
+ Results results = new Results();
+ launcher.execute(request, results);
+ System.out.println(" " + results.passed + " of " + results.total + " pass");
+ allGreen &= results.passed == results.total && results.total > 0;
+ }
+ System.out.println();
+ System.exit(allGreen ? 0 : 1);
+ }
+
+ private static final class Results implements TestExecutionListener {
+
+ private int total;
+ private int passed;
+
+ @Override
+ public void executionFinished(TestIdentifier test, TestExecutionResult result) {
+ boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL;
+ if (!test.isTest()) {
+ // A container that fails (for example the Spring context cannot start) takes its tests with it.
+ if (!ok) {
+ total++;
+ System.out.println(" [FAIL] " + test.getDisplayName() + " could not start");
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ return;
+ }
+ total++;
+ if (ok) {
+ passed++;
+ System.out.println(" [PASS] " + test.getDisplayName());
+ } else {
+ System.out.println(" [FAIL] " + test.getDisplayName());
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ }
+
+ private static void printReason(Throwable throwable) {
+ Throwable root = throwable;
+ while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) {
+ root = root.getCause();
+ }
+ String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage();
+ message.strip().lines()
+ .map(String::strip)
+ .filter(line -> !line.isEmpty())
+ .limit(6)
+ .forEach(line -> System.out.println(" " + line));
+ }
+ }
+
+ private Check() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ImportControllerTest.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ImportControllerTest.java
new file mode 100644
index 0000000..6dca681
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ImportControllerTest.java
@@ -0,0 +1,95 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.amigoscode.batching.imports.ImportController;
+import com.amigoscode.batching.imports.ImportService;
+import com.amigoscode.batching.imports.ImportStrategy;
+import com.amigoscode.batching.product.ProductRow;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+/**
+ * Unit tests for the HTTP contract: no Spring context, no database, ImportService is a stub. They
+ * pass from the start and must keep passing whatever you change behind the controller.
+ */
+@Tag("baseline")
+class ImportControllerTest {
+
+ private static final String CSV = "sku,name,price\nSKU-1,Mug,7.50\nSKU-2,Kettle,24.00\n";
+
+ @Test
+ @DisplayName("HTTP: POST /api/imports/products reads the CSV row by row and returns how many rows were imported")
+ void importReturnsTheRowCount() throws Exception {
+ List received = new ArrayList<>();
+ ImportStrategy[] strategy = new ImportStrategy[1];
+
+ api((chosen, rows) -> {
+ strategy[0] = chosen;
+ rows.forEach(received::add);
+ return received.size();
+ }).perform(post("/api/imports/products?strategy=copy").contentType("text/csv").content(CSV))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.strategy").value("copy"))
+ .andExpect(jsonPath("$.rows").value(2));
+
+ assertThat(strategy[0]).isEqualTo(ImportStrategy.COPY);
+ assertThat(received).extracting(ProductRow::sku).containsExactly("SKU-1", "SKU-2");
+ }
+
+ @Test
+ @DisplayName("HTTP: an unknown strategy returns 400 UNKNOWN_STRATEGY")
+ void unknownStrategy() throws Exception {
+ api((chosen, rows) -> 0).perform(post("/api/imports/products?strategy=faster").contentType("text/csv").content(CSV))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.code").value("UNKNOWN_STRATEGY"));
+ }
+
+ @Test
+ @DisplayName("HTTP: a row that cannot be read returns 400 BAD_CSV with its line number")
+ void badRow() throws Exception {
+ api((chosen, rows) -> {
+ rows.forEach(row -> { });
+ return 0;
+ }).perform(post("/api/imports/products").contentType("text/csv").content(CSV + "SKU-3,Lamp,cheap\n"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.code").value("BAD_CSV"))
+ .andExpect(jsonPath("$.line").value(4));
+ }
+
+ @Test
+ @DisplayName("HTTP: a row the database refuses returns 422 IMPORT_REJECTED")
+ void rejectedRow() throws Exception {
+ api((chosen, rows) -> {
+ throw new DataIntegrityViolationException("new row violates check constraint \"product_price_check\"");
+ }).perform(post("/api/imports/products").contentType("text/csv").content(CSV))
+ .andExpect(status().isUnprocessableContent())
+ .andExpect(jsonPath("$.code").value("IMPORT_REJECTED"));
+ }
+
+ private interface Importer {
+ long run(ImportStrategy strategy, Iterable rows);
+ }
+
+ /** The controller wired to an ImportService whose importProducts does whatever the test says. */
+ private static MockMvc api(Importer importer) {
+ ImportService stub = new ImportService(null, null, null) {
+ @Override
+ public long importProducts(ImportStrategy strategy, Iterable rows) {
+ return importer.run(strategy, rows);
+ }
+ };
+ return MockMvcBuilders.standaloneSetup(new ImportController(stub))
+ .setControllerAdvice(new ApiExceptionHandler())
+ .build();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/JdbcImportIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/JdbcImportIT.java
new file mode 100644
index 0000000..ae14e93
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/JdbcImportIT.java
@@ -0,0 +1,88 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.db.SqlCall;
+import com.amigoscode.batching.product.ProductRow;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** No JPA: JdbcTemplate.batchUpdate and Postgres COPY. */
+@Tag("task8")
+class JdbcImportIT extends IntegrationTest {
+
+ /** A comma, double quotes, a backslash, a line break and a tab: everything that breaks hand-made CSV. */
+ private static final String AWKWARD_NAME = "Mug, \"large\"\\0.5 l\nsecond line\tand a tab";
+
+ @Test
+ @DisplayName("JdbcTemplate: 2,000 products in 40 round trips, batches of 50")
+ void jdbcTemplateSendsBatches() {
+ Recording recording = record(() -> jdbcImporter.batchInsert(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(40);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("JdbcTemplate: a name with commas, quotes, a backslash and a line break is stored exactly as sent")
+ void jdbcTemplateStoresAwkwardNames() {
+ jdbcImporter.batchInsert(List.of(new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50"))));
+
+ assertThat(jdbc.queryForObject("select name from product", String.class)).isEqualTo(AWKWARD_NAME);
+ }
+
+ @Test
+ @DisplayName("COPY: 2,000 products in one statement")
+ void copyIsOneStatement() {
+ Recording recording = record(() -> jdbcImporter.copy(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(1);
+ assertThat(recording.calls().getFirst().kind()).as("kind of round trip").isEqualTo(SqlCall.Kind.COPY);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("COPY: a name with commas, quotes, a backslash and a line break is stored exactly as sent")
+ void copyStoresAwkwardNames() {
+ List rows = List.of(
+ new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50")),
+ new ProductRow("SKU-2", "Plain name", new BigDecimal("1.00")));
+
+ try {
+ jdbcImporter.copy(rows);
+ } catch (RuntimeException e) {
+ throw new AssertionError("COPY refused the rows: " + rootMessage(e), e);
+ }
+
+ assertThat(jdbc.queryForList("select name from product order by sku", String.class))
+ .containsExactly(AWKWARD_NAME, "Plain name");
+ }
+
+ @Test
+ @DisplayName("COPY: one bad row (a negative price) and nothing is stored, not even the rows before it")
+ void oneBadRowStopsTheWholeCopy() {
+ List rows = new ArrayList<>(Rows.products(2_000));
+ rows.set(1_500, new ProductRow("SKU-1501", "Product 1501", new BigDecimal("-1.00")));
+
+ assertThatThrownBy(() -> jdbcImporter.copy(rows)).as("a negative price is refused by the database");
+
+ assertThat(count("product")).as("products stored").isZero();
+ }
+
+ private static String rootMessage(Throwable e) {
+ Throwable root = e;
+ while (root.getCause() != null && root.getCause() != root) {
+ root = root.getCause();
+ }
+ return root.getMessage();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/OneByOneIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/OneByOneIT.java
new file mode 100644
index 0000000..ad70242
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/OneByOneIT.java
@@ -0,0 +1,42 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.product.ProductRow;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Task 1. These tests pass on purpose: they pin down the problem so you can see what the fixes change. */
+@Tag("task1")
+class OneByOneIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("One by one: 500 rows are 500 INSERTs, each in its own round trip and its own transaction (this documents the problem)")
+ void everyRowIsItsOwnRoundTripAndTransaction() {
+ Recording recording = record(() -> productImporter.importOneByOne(Rows.products(500)));
+
+ assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(500);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(1);
+ assertThat(recording.commits()).as("commits").isEqualTo(500);
+ assertThat(count("product")).as("products stored").isEqualTo(500);
+ }
+
+ @Test
+ @DisplayName("One by one: a bad row in the middle leaves every row before it in the database (this documents the problem)")
+ void aBadRowLeavesHalfAnImport() {
+ List rows = new ArrayList<>(Rows.products(100));
+ rows.set(60, new ProductRow("SKU-61", "Product 61", new BigDecimal("-1.00")));
+
+ assertThatThrownBy(() -> productImporter.importOneByOne(rows)).as("a negative price is refused by the database");
+
+ assertThat(count("product")).as("products left behind by a failed import").isEqualTo(60);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java
new file mode 100644
index 0000000..cee1bca
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java
@@ -0,0 +1,68 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** 500 products with 3 stock levels each: 500 parents and 1,500 children saved in one go. */
+@Tag("task5")
+class ParentsAndChildrenIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Insert: 500 products and 1,500 stock levels go in full batches: 10 product batches and 30 stock level batches")
+ void insertsAreSortedIntoFullBatches() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0)));
+
+ String sent = "\n" + recording.describe();
+ assertThat(recording.roundTrips("insert into product")).as("product INSERT round trips" + sent).isLessThanOrEqualTo(10);
+ assertThat(recording.roundTrips("insert into stock_level")).as("stock level INSERT round trips" + sent).isLessThanOrEqualTo(30);
+ }
+
+ @Test
+ @DisplayName("Insert: stock levels get their ids from a sequence too, at most 31 nextval calls for 1,500 of them")
+ void stockLevelIdsComeFromASequence() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0)));
+
+ assertThat(recording.roundTrips("select nextval('stock_level_seq')"))
+ .as("nextval('stock_level_seq') round trips\n" + recording.describe()).isBetween(1, 31);
+ }
+
+ @Test
+ @DisplayName("Update: a new price and new stock for 500 products takes at most 40 UPDATE round trips, not 1,000")
+ void updatesAreSortedIntoFullBatches() {
+ productImporter.importBatched(Rows.productsWithStock(500, 0));
+
+ Recording recording = record(() -> productImporter.updateAll(Rows.productsWithStock(500, 1)));
+
+ assertThat(recording.roundTrips("update")).as("UPDATE round trips\n" + recording.describe()).isLessThanOrEqualTo(40);
+ assertThat(stockLevelsMatching(1)).as("stock levels that now hold the next day's quantity").isEqualTo(1_500);
+ // Every price went up by 1.00: 1.01 + ... + 6.00 is 1,752.50, plus 500 x 1.00.
+ assertThat(jdbc.queryForObject("select sum(price) from product", java.math.BigDecimal.class))
+ .as("sum of the new prices").isEqualByComparingTo("2252.50");
+ }
+
+ @Test
+ @DisplayName("Insert: every stock level is stored and points to its own product")
+ void everyStockLevelBelongsToItsProduct() {
+ productImporter.importBatched(Rows.productsWithStock(500, 0));
+
+ assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500);
+ assertThat(stockLevelsMatching(0)).as("stock levels whose quantity matches their own product's row").isEqualTo(1_500);
+ }
+
+ /** Stock levels whose quantity is what Rows.productsWithStock(.., day) gave their product. */
+ private long stockLevelsMatching(int day) {
+ return jdbc.queryForObject("""
+ select count(*)
+ from stock_level s
+ join product p on p.id = s.product_id
+ where s.quantity = (cast(substring(p.sku from 5) as int)
+ + ? * case s.warehouse when 'GLA' then 1 when 'LON' then 2 else 3 end) % 10
+ """, Long.class, day);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PersistenceContextIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PersistenceContextIT.java
new file mode 100644
index 0000000..65f3115
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PersistenceContextIT.java
@@ -0,0 +1,63 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.db.ManagedEntities;
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.product.ProductRow;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/**
+ * ManagedEntities counts the entities in the persistence context every time Hibernate flushes.
+ * Every managed entity stays in memory, with a copy of its values for dirty checking, until the
+ * transaction ends or the persistence context is cleared.
+ */
+@Tag("task6")
+class PersistenceContextIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Memory: importing 2,000 products never holds more than 50 entities in the persistence context")
+ void productsAreNotKeptInMemory() {
+ record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(50);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("Memory: with stock levels, never more than 200 entities (50 products and their 150 stock levels)")
+ void productsWithStockAreNotKeptInMemory() {
+ record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0)));
+
+ assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(200);
+ assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500);
+ }
+
+ @Test
+ @DisplayName("Memory: clearing every 50 rows keeps the batches full: still 40 INSERT batches of 50 for 2,000 products")
+ void clearingKeepsTheBatchesFull() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50);
+ }
+
+ @Test
+ @DisplayName("Memory: flush is not commit: a bad row near the end still rolls back the whole import")
+ void flushIsNotCommit() {
+ List rows = new ArrayList<>(Rows.products(2_000));
+ rows.set(1_900, new ProductRow("SKU-1901", "Product 1901", new BigDecimal("-1.00")));
+
+ assertThatThrownBy(() -> productImporter.importBatched(rows)).as("a negative price is refused by the database");
+
+ assertThat(count("product")).as("products left behind by a failed import").isZero();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PriceHistoryIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PriceHistoryIT.java
new file mode 100644
index 0000000..82a6e87
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PriceHistoryIT.java
@@ -0,0 +1,64 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.price.PriceChange;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/** PriceChange ids are UUIDs made in Java, so the id is never null, not even before the first save. */
+@Tag("task7")
+class PriceHistoryIT extends IntegrationTest {
+
+ @Autowired
+ private TransactionTemplate transaction;
+
+ @Test
+ @DisplayName("Assigned ids: saving 1,000 price changes sends no SELECT, only 20 INSERT batches")
+ void noSelectBeforeEveryInsert() {
+ Recording recording = record(() -> priceHistory.record(Rows.products(1_000)));
+
+ String sent = "\n" + recording.describe();
+ assertThat(recording.roundTrips("select")).as("SELECT round trips" + sent).isZero();
+ assertThat(recording.roundTrips("insert into price_change")).as("INSERT round trips" + sent).isEqualTo(20);
+ assertThat(count("price_change")).as("price changes stored").isEqualTo(1_000);
+ }
+
+ @Test
+ @DisplayName("Assigned ids: saveAll() returns the objects you gave it (persist), not copies of them (merge)")
+ void saveAllPersistsTheSameObjects() {
+ List changes = List.of(
+ new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now()),
+ new PriceChange("SKU-2", new BigDecimal("2.00"), Instant.now()));
+
+ List saved = transaction.execute(status -> priceChanges.saveAll(changes));
+
+ assertThat(saved).as("what saveAll returned").hasSize(2);
+ assertThat(saved.get(0)).as("the first object saveAll returned").isSameAs(changes.get(0));
+ assertThat(saved.get(1)).as("the second object saveAll returned").isSameAs(changes.get(1));
+ }
+
+ @Test
+ @DisplayName("Assigned ids: a price change loaded from the database and saved again is updated, not inserted a second time")
+ void aLoadedPriceChangeIsUpdated() {
+ PriceChange original = new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now());
+ transaction.executeWithoutResult(status -> priceChanges.save(original));
+
+ PriceChange loaded = priceChanges.findById(original.getId()).orElseThrow();
+ loaded.setPrice(new BigDecimal("1.50"));
+ transaction.executeWithoutResult(status -> priceChanges.save(loaded));
+
+ assertThat(count("price_change")).as("price change rows").isEqualTo(1);
+ assertThat(jdbc.queryForObject("select price from price_change", BigDecimal.class)).as("the stored price")
+ .isEqualByComparingTo("1.50");
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ProductCsvTest.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ProductCsvTest.java
new file mode 100644
index 0000000..6014c02
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ProductCsvTest.java
@@ -0,0 +1,60 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.batching.imports.BadCsvException;
+import com.amigoscode.batching.imports.ProductCsv;
+import com.amigoscode.batching.product.ProductRow;
+import java.io.StringReader;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** Unit tests: no Spring, no database. The feed format, which none of the tasks change. */
+@Tag("baseline")
+class ProductCsvTest {
+
+ @Test
+ @DisplayName("CSV: quoted fields keep their commas, quotes and line breaks")
+ void quotedFields() {
+ List rows = read("""
+ sku,name,price
+ SKU-1,"Mug, ""large""
+ second line",7.50
+ SKU-2,Plain,1
+ """);
+
+ assertThat(rows).extracting(ProductRow::name).containsExactly("Mug, \"large\"\nsecond line", "Plain");
+ assertThat(rows.get(0).price()).isEqualByComparingTo("7.50");
+ }
+
+ @Test
+ @DisplayName("CSV: every column after price is a warehouse, and its value is the stock there")
+ void warehouseColumns() {
+ List rows = read("""
+ sku,name,price,LON,MAN
+ SKU-1,Mug,7.50,12,3
+ """);
+
+ assertThat(rows.getFirst().stock()).isEqualTo(Map.of("LON", 12, "MAN", 3));
+ }
+
+ @Test
+ @DisplayName("CSV: a price that is not a number is rejected with its line number")
+ void badPrice() {
+ assertThatThrownBy(() -> read("""
+ sku,name,price
+ SKU-1,Mug,7.50
+ SKU-2,Kettle,cheap
+ """))
+ .isInstanceOf(BadCsvException.class)
+ .hasMessageContaining("Line 3");
+ }
+
+ private static List read(String csv) {
+ return ProductCsv.read(new StringReader(csv)).toList();
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/RewriteIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/RewriteIT.java
new file mode 100644
index 0000000..3be1280
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/RewriteIT.java
@@ -0,0 +1,54 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import com.amigoscode.batching.support.ServerSide;
+import java.math.BigDecimal;
+import java.sql.Connection;
+import javax.sql.DataSource;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.postgresql.core.BaseConnection;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Tag("task4")
+class RewriteIT extends IntegrationTest {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Test
+ @DisplayName("Driver: the connections of the pool have reWriteBatchedInserts switched on")
+ void theDriverRewritesBatches() throws Exception {
+ try (Connection connection = dataSource.getConnection()) {
+ boolean rewrite = connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled();
+
+ assertThat(rewrite).as("reWriteBatchedInserts, as the Postgres driver sees it").isTrue();
+ }
+ }
+
+ @Test
+ @DisplayName("Postgres: 2,000 products arrive as multi-row INSERTs, at most 200 INSERT executions instead of 2,000")
+ void postgresExecutesMultiRowInserts() {
+ ServerSide.Executed executed = onTheServer(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(executed.rows("insert into product")).as("rows inserted\n" + executed.describe()).isEqualTo(2_000);
+ assertThat(executed.executions("insert into product")).as("INSERT statements Postgres executed\n" + executed.describe())
+ .isLessThanOrEqualTo(200);
+ }
+
+ @Test
+ @DisplayName("Postgres: every row still arrives exactly once (2,000 rows, and the prices add up)")
+ void everyRowArrivesOnce() {
+ productImporter.importBatched(Rows.products(2_000));
+
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ assertThat(jdbc.queryForObject("select count(distinct sku) from product", Long.class)).as("distinct SKUs").isEqualTo(2_000);
+ // 1.01 + 1.02 + ... + 21.00
+ assertThat(jdbc.queryForObject("select sum(price) from product", BigDecimal.class)).as("sum of the prices")
+ .isEqualByComparingTo("22010.00");
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/SequenceIdsIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/SequenceIdsIT.java
new file mode 100644
index 0000000..bfc5189
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/SequenceIdsIT.java
@@ -0,0 +1,68 @@
+package com.amigoscode.batching;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.product.Product;
+import com.amigoscode.batching.support.IntegrationTest;
+import com.amigoscode.batching.support.Rows;
+import jakarta.persistence.EntityManagerFactory;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.generator.Generator;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Tag("task2")
+class SequenceIdsIT extends IntegrationTest {
+
+ @Autowired
+ private EntityManagerFactory entityManagerFactory;
+
+ @Test
+ @DisplayName("Batched: 2,000 products are sent as 40 INSERT batches of 50, not 2,000 single INSERTs")
+ void insertsAreSentInBatches() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40);
+ assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50);
+ assertThat(count("product")).as("products stored").isEqualTo(2_000);
+ }
+
+ @Test
+ @DisplayName("Batched: the ids come from a sequence, 50 at a time: at most 41 nextval calls for 2,000 products")
+ void idsComeFromTheSequenceFiftyAtATime() {
+ Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000)));
+
+ assertThat(recording.roundTrips("select nextval")).as("nextval round trips\n" + recording.describe())
+ .isBetween(1, 41);
+ }
+
+ @Test
+ @DisplayName("Mapping: Product uses a SEQUENCE generator whose allocationSize equals the sequence's INCREMENT BY")
+ void allocationSizeMatchesTheSequence() {
+ Generator generator = entityManagerFactory.unwrap(SessionFactoryImplementor.class)
+ .getMappingMetamodel().getEntityDescriptor(Product.class).getGenerator();
+
+ assertThat(generator).as("the id generator of Product").isInstanceOf(SequenceStyleGenerator.class);
+ SequenceStyleGenerator sequence = (SequenceStyleGenerator) generator;
+ String name = sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText();
+ Long incrementBy = jdbc.queryForObject("select increment_by from pg_sequences where sequencename = ?", Long.class, name);
+ assertThat(sequence.getOptimizer().getIncrementSize()).as("allocationSize of " + name)
+ .isGreaterThan(1)
+ .isEqualTo(incrementBy.intValue());
+ }
+
+ @Test
+ @DisplayName("Ids: two imports with a plain SQL INSERT in between never hand out the same id twice")
+ void idsNeverClash() {
+ productImporter.importBatched(Rows.products(1_000, "A-"));
+ jdbc.update("insert into product (sku, name, price) values ('PLAIN-1', 'Inserted with plain SQL', 1.00)");
+ productImporter.importBatched(Rows.products(1_000, "B-"));
+
+ assertThat(jdbc.queryForObject("select count(distinct id) from product", Long.class))
+ .as("distinct ids for 2,001 products").isEqualTo(2_001);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/DriverOptions.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/DriverOptions.java
new file mode 100644
index 0000000..3435396
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/DriverOptions.java
@@ -0,0 +1,40 @@
+package com.amigoscode.batching.support;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.util.Properties;
+
+/**
+ * The tests talk to a Postgres started by Testcontainers, on its own URL. Driver options you add to
+ * spring.datasource.url in application.properties (everything after the "?") are copied onto that
+ * URL, so they apply in the tests exactly as they do in ./demo.
+ */
+final class DriverOptions {
+
+ /** "&reWriteBatchedInserts=true", or "" when the URL in application.properties has no options. */
+ static String fromApplicationProperties() {
+ Properties properties = new Properties();
+ try (InputStream in = DriverOptions.class.getResourceAsStream("/application.properties")) {
+ if (in == null) {
+ return "";
+ }
+ properties.load(in);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ String url = properties.getProperty("spring.datasource.url", "");
+ int query = url.indexOf('?');
+ if (query < 0) {
+ return "";
+ }
+ String options = url.substring(query + 1);
+ if (options.endsWith("}")) {
+ options = options.substring(0, options.length() - 1);
+ }
+ return options.isBlank() ? "" : "&" + options;
+ }
+
+ private DriverOptions() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/IntegrationTest.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/IntegrationTest.java
new file mode 100644
index 0000000..9fa6df2
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/IntegrationTest.java
@@ -0,0 +1,86 @@
+package com.amigoscode.batching.support;
+
+import com.amigoscode.batching.db.ManagedEntities;
+import com.amigoscode.batching.db.Recording;
+import com.amigoscode.batching.db.SqlRecorder;
+import com.amigoscode.batching.price.PriceChangeRepository;
+import com.amigoscode.batching.price.PriceHistory;
+import com.amigoscode.batching.product.JdbcProductImporter;
+import com.amigoscode.batching.product.ProductImporter;
+import org.junit.jupiter.api.BeforeEach;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.testcontainers.postgresql.PostgreSQLContainer;
+
+/**
+ * Base class for the *IT tests. They run the real application against a real Postgres started by
+ * Testcontainers (Docker must be running), because how many round trips an import makes is decided
+ * by Hibernate, the mapping and the JDBC driver together, and no mock can tell you that. One
+ * container is shared by every test class.
+ *
+ * The tests never measure time. They count: round trips to the database (SqlRecorder), statements
+ * Postgres executed (pg_stat_statements), entities in the persistence context (ManagedEntities) and
+ * rows in the tables.
+ */
+@SpringBootTest(properties = "spring.main.banner-mode=off")
+public abstract class IntegrationTest {
+
+ private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine")
+ .withCommand("postgres", "-c", "fsync=off", "-c", "shared_preload_libraries=pg_stat_statements");
+
+ static {
+ POSTGRES.start();
+ }
+
+ @DynamicPropertySource
+ static void database(DynamicPropertyRegistry registry) {
+ registry.add("spring.datasource.url", () -> POSTGRES.getJdbcUrl() + DriverOptions.fromApplicationProperties());
+ registry.add("spring.datasource.username", POSTGRES::getUsername);
+ registry.add("spring.datasource.password", POSTGRES::getPassword);
+ }
+
+ @Autowired
+ protected ProductImporter productImporter;
+
+ @Autowired
+ protected JdbcProductImporter jdbcImporter;
+
+ @Autowired
+ protected PriceHistory priceHistory;
+
+ @Autowired
+ protected PriceChangeRepository priceChanges;
+
+ @Autowired
+ protected JdbcTemplate jdbc;
+
+ @BeforeEach
+ void emptyTables() {
+ jdbc.execute("truncate table stock_level, product, price_change");
+ }
+
+ /** Runs the work and returns every round trip it made to Postgres. */
+ protected Recording record(Runnable work) {
+ ManagedEntities.reset();
+ SqlRecorder.start();
+ try {
+ work.run();
+ } catch (RuntimeException e) {
+ SqlRecorder.stop();
+ throw e;
+ }
+ return SqlRecorder.stop();
+ }
+
+ /** Runs the work and returns what Postgres itself executed while it ran (pg_stat_statements). */
+ protected ServerSide.Executed onTheServer(Runnable work) {
+ return ServerSide.during(jdbc, work);
+ }
+
+ protected long count(String table) {
+ return jdbc.queryForObject("select count(*) from " + table, Long.class);
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/Rows.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/Rows.java
new file mode 100644
index 0000000..8153d92
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/Rows.java
@@ -0,0 +1,42 @@
+package com.amigoscode.batching.support;
+
+import com.amigoscode.batching.product.ProductRow;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/** Rows of a feed, made up in the test. */
+public final class Rows {
+
+ public static List products(int count) {
+ return products(count, "SKU-");
+ }
+
+ /** Different prefixes give different SKUs, so two imports in one test do not clash. */
+ public static List products(int count, String skuPrefix) {
+ List rows = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ rows.add(new ProductRow(skuPrefix + i, "Product " + i, price(i)));
+ }
+ return rows;
+ }
+
+ /** Every product with stock in three warehouses. {@code day} changes the price and the stock. */
+ public static List productsWithStock(int count, int day) {
+ List rows = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ rows.add(new ProductRow("SKU-" + i, "Product " + i, price(i).add(BigDecimal.valueOf(day)),
+ Map.of("GLA", (i + day) % 10, "LON", (i + 2 * day) % 10, "MAN", (i + 3 * day) % 10)));
+ }
+ return rows;
+ }
+
+ /** 1.00, 1.01, ... so the total of the prices tells you whether every row arrived once. */
+ public static BigDecimal price(int i) {
+ return BigDecimal.valueOf(100 + i, 2);
+ }
+
+ private Rows() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/ServerSide.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/ServerSide.java
new file mode 100644
index 0000000..83831bd
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/ServerSide.java
@@ -0,0 +1,53 @@
+package com.amigoscode.batching.support;
+
+import java.util.List;
+import java.util.Locale;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/** What Postgres itself executed, read from pg_stat_statements. */
+public final class ServerSide {
+
+ /** One statement as Postgres normalised it, how many times it ran, and how many rows it touched. */
+ public record Statement(String query, long executions, long rows) {
+ }
+
+ public record Executed(List statements) {
+
+ /** How many times Postgres ran a statement that starts with the prefix, for example "insert into product". */
+ public long executions(String prefix) {
+ return matching(prefix).stream().mapToLong(Statement::executions).sum();
+ }
+
+ public long rows(String prefix) {
+ return matching(prefix).stream().mapToLong(Statement::rows).sum();
+ }
+
+ private List matching(String prefix) {
+ return statements.stream()
+ .filter(statement -> statement.query().toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT)))
+ .toList();
+ }
+
+ public String describe() {
+ StringBuilder text = new StringBuilder("Postgres executed:");
+ statements.forEach(statement -> text.append(String.format("%n%,d x %s", statement.executions(),
+ statement.query().length() > 90 ? statement.query().substring(0, 90) + "..." : statement.query())));
+ return text.toString();
+ }
+ }
+
+ static Executed during(JdbcTemplate jdbc, Runnable work) {
+ jdbc.execute("select pg_stat_statements_reset()");
+ work.run();
+ return new Executed(jdbc.query("""
+ select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows
+ from pg_stat_statements
+ where dbid = (select oid from pg_database where datname = current_database())
+ and query !~* 'pg_stat_statements'
+ order by calls desc
+ """, (row, number) -> new Statement(row.getString(1), row.getLong(2), row.getLong(3))));
+ }
+
+ private ServerSide() {
+ }
+}
diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/16-batch-writes/start/src/test/resources/logback-test.xml
new file mode 100644
index 0000000..82166a4
--- /dev/null
+++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/resources/logback-test.xml
@@ -0,0 +1,11 @@
+
+
+
+ %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n
+
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/INTERVIEW_TASKS.md b/java/concepts/junior-mid/17-testing-with-a-real-database/INTERVIEW_TASKS.md
new file mode 100644
index 0000000..25d119c
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/INTERVIEW_TASKS.md
@@ -0,0 +1,265 @@
+# Interview Tasks — Testing With a Real Database
+
+> **In `start/`, `./check` FAILS on purpose: 9 of 24 checks pass.** Tasks 2, 4, 5, 6 and 7 turn the
+> other 15 green. Tasks 1 and 3 have checks that pass from the start: they document how H2,
+> Postgres and `@DataJpaTest` behave. Task 8 is an inspection task: you run things, look, and answer
+> questions.
+
+Do the tasks in order. A green test only tells you something if it can go red. In every task you
+first make your tests see the problem, then fix the code, then look at what your tests actually did.
+
+Stuck, or want the explanation? The same task number in [`TASKS_GUIDED.md`](TASKS_GUIDED.md) walks
+you through it with the expected output.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+**Rules:** work in `start/`. Never edit anything under `check/`. Do not rename `findTopRated`,
+`findByShelf`, `subscribe`, `BookRepositoryTest` or `SubscriptionServiceTest`: the checks use those
+names. Read "Two kinds of test in this project" in the [README](README.md) first: here the checks
+judge your tests, not only your code.
+
+---
+
+## Task 1: See It Break (10 min)
+
+**Story:** *The suite is green, CI is green, the release went out. On day one: the "top rated" page
+shows a book with no reviews at number 1, audiobooks cannot be added, nobody can subscribe to the
+newsletter, and shelves come back in a strange order. Before you change anything, find out why the
+tests did not notice.*
+
+**Steps:**
+1. `docker compose up -d`, then `./demo`. How many tests pass? How many features work in
+ production?
+2. Read the database table in the demo output. Which database did each test class use? Which test
+ used no database at all?
+3. For each broken feature, find the test that is supposed to cover it. What does that test do, and
+ why is it green?
+4. Open `catalogue/BookRepositoryTest`. Its `@DataJpaTest` turns Flyway off. Why? What builds the
+ tables instead?
+5. `./check 1`. Each check runs the same SQL on H2 and on Postgres. Write down the three
+ differences.
+
+**Acceptance Criteria** (`./check 1`, already passing: these checks document the differences)
+- [ ] You can say which database each of your test classes ran on
+- [ ] You can name, for each of the four bugs, why the test was green
+- [ ] You can explain why "H2 in PostgreSQL mode" is not Postgres
+
+**Hints:**
+- Postgres sorts NULL as the largest value
+- `SubscriptionServiceTest` never sends any SQL anywhere
+- Where does the `CHECK` constraint on `book.format` live? Where does the H2 schema come from?
+
+---
+
+## Task 2: Run the Repository Tests on Postgres (20 min)
+
+**Story:** *Make `BookRepositoryTest` run against the database production uses, with the schema
+production uses. Then fix whatever it finds.*
+
+**Acceptance Criteria** (`./check 2`)
+- [ ] Production: top rated lists the best rated books first, never an unrated one ahead of them
+- [ ] Production: an `AUDIOBOOK` can be added
+- [ ] `BookRepositoryTest` runs on PostgreSQL, not H2
+- [ ] Its schema comes from the Flyway migrations, not from Hibernate
+- [ ] Your suite catches the top rated bug: with the `start/` query put back, a test fails
+- [ ] Your suite catches the missing migration: with `AUDIOBOOK` rejected again, a test fails
+- [ ] `./demo` shows your tests turn red before your fix and green after it
+
+**Hints:**
+- Testcontainers starts a throwaway Postgres in Docker. Boot's `@ServiceConnection` on the container
+ field tells Spring where it is: no URL to write
+- Remove the properties that turned Flyway off and told Hibernate to create the tables
+- Make the tests red first, then fix the code: a query in `BookRepository` and a new migration file.
+ Never edit `V1`: it has already run in production
+
+---
+
+## Task 3: Inspect Which Database Your Test Really Used (10 min)
+
+**Story:** *"The test was supposed to use Postgres" is a sentence people say after an incident. Prove
+which database each test talks to, and find out what `@DataJpaTest` does on its own.*
+
+**Steps:**
+1. `./inspect`. For each test class: which database, which URL, and where did its schema come from?
+2. In `start/` as you received it, `BookRepositoryTest` had no URL at all, and
+ `application.properties` points at Postgres on port 5456. Yet it ran on H2. Who replaced it?
+3. In `BookRepositoryTest`, comment out `@ServiceConnection` (keep the container) and run
+ `./inspect`. What happened, and what is the error? Put it back.
+4. `./check 3`. Write down the three rules it documents.
+5. Contexts: how many Spring contexts did your suite start? Which classes used which?
+
+**Acceptance Criteria** (`./check 3`, already passing: these checks document Spring Boot's behaviour)
+- [ ] You can say when `@DataJpaTest` swaps your DataSource for an embedded database, and how to stop it
+- [ ] You can explain the difference between `@ServiceConnection` and `@DynamicPropertySource`
+- [ ] You can say what a `@DataJpaTest` loads, compared with a `@SpringBootTest`
+
+---
+
+## Task 4: Replace the Fake Where It Hides the SQL (15 min)
+
+**Story:** *`subscribe` is one `INSERT ... ON CONFLICT`. H2 cannot run it, so someone tested the
+service with a fake instead. The fake does what we believe the SQL does. Find out what it really
+does.*
+
+**Acceptance Criteria** (`./check 4`)
+- [ ] Production: `ann@example.com` then `Ann@Example.COM` gives one subscriber and
+ `ALREADY_SUBSCRIBED`, with no error
+- [ ] Your suite catches the `ON CONFLICT` bug: with the `start/` SQL put back, a test fails
+- [ ] `SubscriptionServiceTest` still tests the service's logic with the fake, with no Spring and no
+ database (already passing: keep it that way)
+
+**Hints:**
+- A new `@DataJpaTest`, `SubscriberRepositoryTest`, on Postgres, calling `subscribe` directly
+- Read the unique index in `V1__create_catalogue.sql`. `ON CONFLICT (...)` must name exactly what an
+ index is built on
+- Which tests in `SubscriptionServiceTest` are about the service, and which pretend to be about SQL?
+
+---
+
+## Task 5: One Container, One Context per Kind of Test (20 min)
+
+**Story:** *The suite now runs on Postgres and takes noticeably longer. Every new test class that
+copies the container lines adds another container and another Spring context. Make the whole suite
+share one of each kind.*
+
+**Steps before you change anything:**
+1. `./inspect`. How many Postgres servers did your suite talk to? How many Spring contexts did it
+ start, and how long did each take?
+2. `BookRepositoryTest` and `ShelfTest` are both `@DataJpaTest`. Why do they get different contexts?
+
+**Acceptance Criteria** (`./check 5`)
+- [ ] Every Spring test runs on PostgreSQL: no H2 left, including `ShelfTest` and `CatalogueApiTest`
+- [ ] One Postgres container for the whole run
+- [ ] At most 2 Spring contexts: one for the `@DataJpaTest` classes, one for `@SpringBootTest`
+- [ ] Inspect again: what changed in the numbers?
+
+**Hints:**
+- An abstract base class with the container as a static field, started in a static block
+- Spring caches a context by its whole configuration: properties, `@Import`, `@MockitoBean`,
+ `@ActiveProfiles`, `@DirtiesContext`, the container fields. Anything different is a new context
+- `@DirtiesContext` throws away the context. Does it throw away the rows in the container?
+- Expect some tests to go red when they share a database. That is Task 6
+
+---
+
+## Task 6: Tests That Own Their Data (20 min)
+
+**Story:** *Since the suite shares one database, `CatalogueApiTest` and `ShelfTest` fail, depending on
+what ran before them. `CatalogueApiTest` is `@Transactional`, "so it rolls back". Find out what it
+really rolls back.*
+
+**Acceptance Criteria** (`./check 6`)
+- [ ] Every test that passes in the full run also passes on its own
+- [ ] Every test gives the same result with classes and methods from Z to A (passes in `start/`,
+ where every class had a database of its own; sharing one in Task 5 breaks it)
+- [ ] No test depends on the value of a generated id: the suite stays green with every id sequence
+ moved on by 1000 before each test
+- [ ] `./check` baseline is green again
+
+**Hints:**
+- Try the obvious fix first: in `listsTheShelf`, save the books with `BookRepository` instead of
+ relying on `addsABook`. Run it. Where did your books go?
+- The HTTP request is handled on a server thread, in its own transaction
+- Rolled back data is gone. Is a rolled back id given back?
+- Clean before each test, not after: then any test can run first
+
+---
+
+## Task 7: Order You Can Rely On (10 min)
+
+**Story:** *A shelf must list its books in the order they were added. `ShelfTest` says it does. It
+says so on Postgres too. Make it prove it.*
+
+**Acceptance Criteria** (`./check 7`)
+- [ ] Production: a shelf keeps its order after one of its books is rated
+- [ ] Your suite catches the missing `ORDER BY`: with the `start/` query put back, a test fails
+
+**Hints:**
+- Make the test red first. What does Postgres do to a row on UPDATE?
+- `findByShelf` is a derived query. What does it put after `where`?
+
+---
+
+## Task 8: Compare, and the Test Pyramid (10 min)
+
+**Story:** *"How would you test this service?" is the interview question. Collect the evidence, then
+answer it.*
+
+**Steps:**
+1. `./demo`. Compare with Task 1, line by line.
+2. `./inspect`. Compare containers, contexts and start-up times with Task 5 step 1.
+3. Which of your tests need Docker? Which do not? How long does each kind take?
+4. Look at the rows left behind after the last test. Why are there any?
+5. Your CI has no Docker. What are your options?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can say which tests should use a fake, which a real database, and which the whole app
+- [ ] You can explain how the suite starts one container and keeps Spring's context cache warm
+- [ ] You can say when an in-memory database is acceptable
+
+---
+
+## Questions to Ask Afterwards
+
+Answer out loud, in full sentences, before reading the answer in brackets.
+
+- Why not test the repository on H2? (H2 is a different database. Its "PostgreSQL mode" copies some
+ syntax, not the behaviour: here it sorts NULLs differently, returns rows in a different order,
+ cannot parse the real migration or `ON CONFLICT (...)`, and its schema came from Hibernate instead
+ of the migrations. A green test on H2 proves the code works on H2.)
+- What is Testcontainers? (A library that starts real services, here Postgres, in throwaway Docker
+ containers from a test, and removes them afterwards. The test talks to the same database version
+ as production, built by the same migrations.)
+- How does Spring Boot find the container? (`@ServiceConnection` on the container field: Boot reads
+ the URL, user and password from it. The older way is `@DynamicPropertySource`, a static method
+ that registers `spring.datasource.url` and friends from the container.)
+- What does `@DataJpaTest` do to your database? (It is a slice: only JPA, repositories, Flyway and a
+ DataSource, and every test in a transaction that is rolled back. In Spring Boot 4 it replaces a
+ DataSource whose URL comes from ordinary properties with an embedded database if one is on the
+ classpath. It keeps a `@ServiceConnection` container or a `@DynamicPropertySource` URL. Use
+ `@AutoConfigureTestDatabase(replace = NONE)` to keep any URL.)
+- Your suite takes 3 minutes because of containers. What do you do? (One container per JVM: a static
+ field started once, shared by every test class, not a JUnit `@Container` per class. Keep the test
+ configuration identical across classes so Spring's context cache reuses contexts: no stray
+ properties, no `@MockitoBean` in one class only, no `@DirtiesContext`. Locally,
+ `testcontainers.reuse.enable=true` can keep a container between runs; never rely on it in CI.)
+- Is a mock of the repository enough? (For the service's logic, yes, and a hand-written fake is often
+ clearer. For the repository itself, no: a mock or fake does what you believe the SQL does. Queries,
+ constraints, migrations and transactions need the real database.)
+- Your test is `@Transactional`, so it rolls back. Is the database clean? (Only of what ran in that
+ transaction. An HTTP call to the running server, an `@Async` method or a `REQUIRES_NEW` runs in
+ another transaction and commits. And the server cannot see what the test wrote in its own
+ uncommitted transaction. Sequences are not rolled back either.)
+- A test passes alone and fails in the suite, or the other way round. Why? (It shares state with
+ another test: rows one left behind, rows one created that the other needs, or an id it assumes.
+ Each test should create its own data and start from a known state, for example by truncating the
+ tables before it runs.)
+- Why not assert `id == 1`? (Ids come from a sequence. Rollbacks do not give them back, other tests
+ use them, a reused database continues where it was. Assert on the id the code returned.)
+- Why did the order change after an UPDATE? (Without `ORDER BY` the database returns rows in whatever
+ order is cheapest. In Postgres an UPDATE writes a new version of the row, usually after the
+ others, so a plain scan returns it last. SQL promises no order without `ORDER BY`.)
+- When is an in-memory database acceptable? (When the code under test does not depend on the
+ database: plain CRUD in a prototype, or a library that must run on several databases and is tested
+ on each. Not when production runs on a specific database with its own SQL, types and constraints.)
+- What does the test pyramid look like for a Spring service? (Many fast unit tests for logic, with
+ fakes. A layer of integration tests on the real database for repositories, queries, migrations and
+ transactions. A few end-to-end tests through HTTP. Docker is a requirement for the middle layer, on
+ laptops and in CI.)
+
+## Tips for Interviewers
+
+- The most common answer is "I use H2 for tests". Ask what Postgres-specific SQL, types or constraints
+ the service uses, and how H2 would know about them.
+- Ask the candidate to predict `./demo` in Task 1 before running it. A strong candidate expects the
+ NULL ordering problem before seeing it.
+- Watch Task 4. A candidate who deletes the fake test has missed the point: the fake is right for the
+ logic, wrong for the SQL.
+- Task 5 separates levels. A junior adds `@Container` to every class. A mid-level candidate shares one
+ container. A strong one explains why two `@DataJpaTest` classes got two contexts, and what
+ `@DirtiesContext` does not clean.
+- In Task 6, ask why the `@Transactional` HTTP test could not see its own rows. A candidate who
+ answers "the server runs in another thread with its own transaction" understands what a test
+ transaction is.
+- For senior candidates: how do you run this in CI without Docker-in-Docker, and how do you keep a
+ suite of 2,000 integration tests under five minutes?
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/README.md b/java/concepts/junior-mid/17-testing-with-a-real-database/README.md
new file mode 100644
index 0000000..3d4e71a
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/README.md
@@ -0,0 +1,199 @@
+# Testing With a Real Database — Testcontainers Instead of H2 and Mocks
+
+> **In `start/`, `./check` FAILS on purpose: 9 of 24 checks pass.** That is the exercise, not a
+> broken checkout. Tasks 2, 4, 5, 6 and 7 turn the other 15 green.
+
+A bookshop's test suite is green. Every test passes, in a few seconds, with no Docker. Then the code
+goes to production on Postgres and four things break on the first day: the "top rated" page shows a
+book nobody has reviewed at number 1, adding an audiobook fails, subscribing to the newsletter
+fails for everyone, and a shelf lists its books in a different order after somebody rates one.
+
+The tests ran on H2, a database that pretends to be Postgres, and on a hand-written fake. This
+project lets you watch your own tests say GREEN while production says BROKEN, then move the tests
+onto a real Postgres with Testcontainers, keep them fast, and keep them from tripping over each
+other.
+
+It answers the interview questions students most often get wrong:
+
+- "How do you test your repository layer? Why not H2?"
+- "What is Testcontainers? How do you stop it from making the test suite slow?"
+- "`@DataJpaTest` or `@SpringBootTest`? What does `@DataJpaTest` do with your database?"
+- "Is a mock of the repository enough? When is a fake fine?"
+- "Your test is `@Transactional`, so it rolls back. Is the database clean after it?"
+- "A test passes on its own and fails in the full suite. Why?"
+
+## Tech Stack
+
+- **Java 25**, **Spring Boot 4**, Spring Data JPA (**Hibernate 7**), Flyway
+- **PostgreSQL 17** in Docker
+- JUnit 6 (Jupiter), AssertJ, **Testcontainers 2**, H2 (in `start/`, as the tests use it; in both folders,
+ for the checks that compare it with Postgres)
+
+## What you need
+
+- JDK 25
+- Docker, running
+
+## Getting Started
+
+Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see
+`./demo` (same for `inspect` and `check`).
+
+```bash
+cd start
+docker compose up -d # the "production" Postgres, on port 5456
+./demo # your tests say GREEN, production says BROKEN
+./check # 9 of 24 pass: that is your starting point
+```
+
+The first run downloads Maven, the dependencies and the Postgres image, so it takes a few minutes.
+
+When you are finished: `docker compose down -v`.
+
+## The three tools
+
+### `./demo` — your tests next to production
+
+Runs your test suite, one line per test, and shows which database each test class used. Then it
+starts the real application on the Postgres from `compose.yaml` (emptied first, then built by the
+Flyway migrations, as in production) and tries the same four features. The last line is the
+verdict:
+
+```
+RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. 8 of 8 tests pass, and 4 of 4 features are broken on Postgres.
+```
+
+### `./inspect` — what your tests really did
+
+Runs your test suite once with a recorder attached and prints what happened underneath: the
+database each test class talked to (H2 or Postgres, and its URL), where each schema came from
+(Flyway or Hibernate), how many Postgres containers and Spring contexts were started and how long
+each context took to start, and the rows left in the tables after the last test.
+
+### `./check` — are the acceptance criteria met?
+
+`./check 2` runs the checks for Task 2 and prints one line per criterion. `./check` runs everything.
+`./mvnw verify` runs the same checks the usual Maven way.
+
+**Never edit, delete or disable anything under `check/`.**
+
+## Two kinds of test in this project
+
+This project is about **your tests**, so it has two layers. Keep them apart:
+
+| | Your test suite | The acceptance checks |
+|---|---|---|
+| Where | `src/test/java/com/amigoscode/realdb/` (everything except `check/`) | `src/test/java/com/amigoscode/realdb/check/` |
+| Who writes it | You. In `start/` it runs on H2 and a fake, and it is green | Given. You never change it |
+| Run by | `./mvnw test`, `./demo`, `./inspect` | `./check`, `./mvnw verify` |
+
+The checks ask two kinds of question.
+
+**"Production: ..."** checks run the code in `src/main` with its Flyway migrations against the
+checks' own Postgres container. They do not look at your tests. They tell you the code works.
+
+**"Your suite: ..."** checks run your test classes through the JUnit launcher, the same way an IDE
+does, and judge the suite itself:
+
+- **Which database did it use?** A Spring test listener, registered in
+ `src/test/resources/META-INF/spring.factories`, notes for every test class the Spring context it
+ got, the database behind it (product, URL, Postgres's server id), and whether its schema has a
+ `flyway_schema_history` table. Counting distinct server ids counts containers; counting distinct
+ contexts counts context starts. Nothing is timed.
+- **Would it catch the bug?** The check puts one bug from `start/` back into the fixed code and runs
+ your suite again. Three bugs are repository queries: the checks wrap `BookRepository` and
+ `SubscriberRepository` in your test contexts, and while a bug is switched on, `findTopRated`,
+ `findByShelf` or `subscribe` runs the `start/` SQL. The fourth adds a constraint that rejects
+ `AUDIOBOOK` to any database your tests built with Flyway, as if V2 had never run. Your suite
+ "catches" the bug if a test that is green without it turns red with it. A test only counts if it
+ is also green when the suite runs a second time without the bug, so a test that breaks for some
+ other reason cannot catch anything by accident. This is called mutation testing.
+- **Is every test independent?** Your suite runs A to Z, then Z to A, then every test on its own,
+ then with every id sequence moved on by 1000 just before each test. A test may not change its
+ result between these runs.
+
+The wrappers do nothing during `./mvnw test`: only a check switches a bug on. They are the same for
+every test class, so they never stop two of your classes from sharing a Spring context. Because the
+checks call them by name, **do not rename `findTopRated`, `findByShelf` or `subscribe`**, and keep
+the test class names `BookRepositoryTest` and `SubscriptionServiceTest`.
+
+## The code
+
+```
+start/src/main/java/com/amigoscode/realdb/
+├── catalogue/
+│ ├── Book.java the entity: title, format, rating (null = no reviews), shelf
+│ ├── Format.java PAPERBACK, HARDCOVER, EBOOK, AUDIOBOOK (new)
+│ ├── BookRepository.java findTopRated, findByShelf. TWO BUGS ARE HERE
+│ ├── CatalogueService.java add, rate, top rated, shelf
+│ └── CatalogueController.java /api/books, /api/shelves/{shelf}
+└── subscription/
+ ├── SubscriberRepository.java subscribe: one INSERT ... ON CONFLICT. A BUG IS HERE
+ └── SubscriptionService.java checks the address, then subscribes
+start/src/main/resources/db/migration/
+└── V1__create_catalogue.sql the real schema. A MIGRATION IS MISSING
+
+start/src/test/java/com/amigoscode/realdb/ YOUR TEST SUITE
+├── catalogue/
+│ ├── BookRepositoryTest.java @DataJpaTest on H2
+│ ├── ShelfTest.java @DataJpaTest on H2, with one extra property
+│ └── CatalogueApiTest.java @SpringBootTest over HTTP, H2 in PostgreSQL mode, @Transactional
+├── subscription/
+│ ├── SubscriptionServiceTest.java unit tests with...
+│ └── FakeSubscriberRepository.java ...an in-memory fake
+└── check/ the acceptance checks and ./demo, ./inspect. Never edit
+```
+
+## Two ways to work
+
+- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and
+ hints for each task. Use this if you want to work it out yourself.
+- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same eight tasks, step by step, with the output you
+ should see and an explanation of why. Use this to learn the concept, or when you are stuck.
+
+Both files use the same task numbers.
+
+| Task | What you do | Checked by |
+|---|---|---|
+| 1 | See it break: green on H2, broken on Postgres | `./check 1` (passes: it documents the differences) |
+| 2 | Run the repository tests on Postgres, fix what they find | `./check 2` |
+| 3 | Inspect: which database did your test really use? | `./check 3` (passes: it documents what `@DataJpaTest` does) |
+| 4 | Replace the fake where it hides the SQL | `./check 4` |
+| 5 | One container, one context per kind of test | `./check 5` |
+| 6 | Tests that own their data: the `@Transactional` trap | `./check 6` |
+| 7 | Order you can rely on | `./check 7` |
+| 8 | Compare, and the test pyramid | you answer questions |
+
+## Solution
+
+`solution/` is the same project with every task done: `cd solution && ./check` prints 24 of 24.
+
+To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`).
+
+
+Spoiler: the bugs and the fixes
+
+**Four bugs that H2 and the fake hide.** Each one was confirmed on H2 2.4 and Postgres 17.
+
+| Bug | On H2 / the fake | On Postgres | Fix |
+|---|---|---|---|
+| `order by rating desc` | NULLs sort last: unrated books at the bottom | NULLs sort first in DESC: an unrated book is number 1 | `order by b.rating desc nulls last, b.id` |
+| `AUDIOBOOK` added to the enum, not to the schema | Hibernate builds the H2 schema from the enum, so it accepts it | V1's check constraint rejects it | `V2__allow_audiobooks.sql` |
+| `on conflict (email) do nothing` | H2 cannot even parse it, so the service was tested with a fake that "worked" | No unique index matches `(email)`: the index is on `lower(email)`. Every subscribe fails | `on conflict (lower(email)) do nothing` |
+| `findByShelf` with no `ORDER BY` | Rows come back in primary key order | An UPDATE writes the row's new version after the others: the updated book comes back last | `order by b.addedAt, b.id` |
+
+**The tests.**
+
+- One Postgres container for the whole run: a static field in an abstract `PostgresTest` that every
+ database test extends, started once, with `@ServiceConnection`. The schema comes from the Flyway
+ migrations.
+- `@DataJpaTest` keeps a `@ServiceConnection` container. A URL from `application.properties` it
+ replaces with an embedded H2 unless you add `@AutoConfigureTestDatabase(replace = NONE)`.
+- Same container, same configuration in every class: 2 Spring contexts (one `@DataJpaTest`, one
+ `@SpringBootTest`) instead of one per class.
+- The fake stays for the service's own logic; the SQL gets a `@DataJpaTest` on Postgres.
+- No `@Transactional` on the HTTP test: the server commits on its own thread. Every test starts by
+ truncating the tables, and asserts on ids it got back, never on `1`.
+- An order you rely on is an `ORDER BY` you wrote, and a test that updates a row before reading.
+
+
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/TASKS_GUIDED.md b/java/concepts/junior-mid/17-testing-with-a-real-database/TASKS_GUIDED.md
new file mode 100644
index 0000000..abc5a08
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/TASKS_GUIDED.md
@@ -0,0 +1,893 @@
+# Guided Tasks — Testing With a Real Database
+
+The same eight tasks as [`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md), step by step: the command to
+run, the output you should see, why it happens, and the change to make.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+Ports, ids, server ids and timings will differ on your machine. The test names, the counts and the
+`RESULT` line should match.
+
+**Before you start**
+
+```bash
+cd start
+docker compose up -d
+```
+
+---
+
+## Task 1: See It Break
+
+No code in this task. You are collecting evidence.
+
+### Run it
+
+```bash
+./demo
+```
+
+### What you should see
+
+```
+1. YOUR TEST SUITE (src/test/java, everything outside check/)
+
+ [GREEN] BookRepositoryTest.savesAnAudiobook
+ [GREEN] BookRepositoryTest.topRatedComesBestFirstAndUnratedBooksLast
+ [GREEN] CatalogueApiTest.addsABook
+ [GREEN] CatalogueApiTest.listsTheShelf
+ [GREEN] ShelfTest.shelfListsBooksInTheOrderTheyWereAdded
+ [GREEN] SubscriptionServiceTest.aNewAddressIsSubscribed
+ [GREEN] SubscriptionServiceTest.rejectsSomethingThatIsNotAnEmailAddress
+ [GREEN] SubscriptionServiceTest.theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce
+
+ 8 tests: 8 green, 0 red, in 6776 ms. The database each test class used:
+
+ test class database url
+ ----------------------- ---------- ------------------------------------------------
+ BookRepositoryTest H2 2.4.240 jdbc:h2:mem:f6088562-538e-4f63-a024-e4aec2f7e023
+ CatalogueApiTest H2 2.4.240 jdbc:h2:mem:catalogue
+ ShelfTest H2 2.4.240 jdbc:h2:mem:6646fafe-5a6a-417e-a24d-9d8d119cae5a
+ SubscriptionServiceTest none no Spring context: a plain unit test
+
+2. PRODUCTION: the same features, the code in src/main, on PostgreSQL 17.12
+ (compose.yaml, jdbc:postgresql://localhost:5456/shop), schema from Flyway: V1 create catalogue
+
+ [BROKEN] Top rated
+ added: Dune 4.8, Emma 3.9, No Reviews Yet (no rating), Hamlet 4.2
+ top 3: No Reviews Yet (no rating), Dune 4.8, Hamlet 4.2
+ A book nobody has reviewed is ahead of the best rated ones.
+ [BROKEN] Add an audiobook
+ ERROR: new row for relation "book" violates check constraint "book_format_check"
+ [BROKEN] Subscribe ann@example.com, then Ann@Example.COM
+ ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
+ [BROKEN] Shelf "classics" after a review of Beloved
+ added: Beloved, Middlemarch, Rebecca. Then Beloved got a rating.
+ listed: Middlemarch, Rebecca, Beloved
+ Not the order they were added in.
+
+RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. 8 of 8 tests pass, and 4 of 4 features are broken on Postgres.
+```
+
+Every test is green. Every feature is broken.
+
+### Why each test stayed green
+
+Look at the database column first: three test classes ran on H2, one on no database at all.
+
+| Feature | The test | Why it is green |
+|---|---|---|
+| Top rated | `BookRepositoryTest.topRated...` | Same query, same data. H2 sorts the NULL rating **last** in `desc` order, Postgres sorts it **first** |
+| Audiobook | `BookRepositoryTest.savesAnAudiobook` | `spring.flyway.enabled=false`: Hibernate built the H2 tables from the entities, and the entity knows `AUDIOBOOK`. The real schema is `V1__create_catalogue.sql`, whose `CHECK` constraint does not |
+| Subscribe | `SubscriptionServiceTest` | A fake repository. The SQL never runs anywhere |
+| Shelf order | `ShelfTest` | It never updates a row. And on H2 rows come back in primary key order anyway |
+
+`CatalogueApiTest` uses "H2 in PostgreSQL mode" (`MODE=PostgreSQL` in its URL). That mode copies
+some Postgres syntax. It is still H2: same sort order, same storage, same parser.
+
+### The differences, in plain SQL
+
+```bash
+./check 1
+```
+
+```
+Task 1: See it break: H2 and Postgres disagree
+ [PASS] H2 vs Postgres: without ORDER BY, H2 returns rows by primary key, Postgres returns the row you just updated last
+ [PASS] H2 vs Postgres: ORDER BY rating DESC puts the NULL rating last on H2 (PostgreSQL mode), first on Postgres
+ [PASS] H2 vs Postgres: H2 cannot parse the real schema's index on lower(email) or ON CONFLICT (email); Postgres can, and rejects ON CONFLICT (email) because no index matches it
+ 3 of 3 pass
+```
+
+These pass on purpose. Each one runs the same statements on H2 and on a real Postgres and pins down
+what each database answered (see `check/H2VersusPostgresIT.java`).
+
+> H2's own documentation suggests adding `DEFAULT_NULL_ORDERING=HIGH` to the URL for PostgreSQL
+> mode. That would fix one of the four. To configure a difference away, you first have to know about
+> it, and that is exactly what you do not know before production tells you.
+
+---
+
+## Task 2: Run the Repository Tests on Postgres
+
+**The idea:** test the repository against the database production uses, built by the migrations
+production uses. Testcontainers starts a throwaway Postgres in Docker for the test run.
+
+### Step 1: give BookRepositoryTest a real Postgres
+
+In `catalogue/BookRepositoryTest`, delete the class comment (it is no longer true) and replace:
+
+```java
+@DataJpaTest(properties = {
+ "spring.flyway.enabled=false",
+ "spring.jpa.hibernate.ddl-auto=create-drop"})
+class BookRepositoryTest {
+```
+
+with:
+
+```java
+@DataJpaTest
+class BookRepositoryTest {
+
+ @ServiceConnection
+ static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine");
+
+ static {
+ POSTGRES.start();
+ }
+```
+
+Imports: `org.springframework.boot.testcontainers.service.connection.ServiceConnection` and
+`org.testcontainers.postgresql.PostgreSQLContainer`. The dependencies are already in `pom.xml`.
+
+Three things happened:
+
+- **The container.** A static field, started once in a static block, before Spring starts. Same
+ image as `compose.yaml`.
+- **`@ServiceConnection`.** Spring Boot reads the JDBC URL, user and password from the container. You
+ write no URL. (The older way, still fine, is a `@DynamicPropertySource` method that registers
+ `spring.datasource.url`, `username` and `password` from `POSTGRES::getJdbcUrl` and friends. The
+ checks' own base class `check/support/ProductionTest.java` does it that way.)
+- **No more properties.** Flyway is back on, so the schema comes from `db/migration`, and Hibernate
+ no longer invents one.
+
+### Step 2: watch it go red
+
+Do not fix anything yet. A test you have never seen fail proves nothing.
+
+```bash
+./demo
+```
+
+```
+ [RED] BookRepositoryTest.savesAnAudiobook
+ ERROR: new row for relation "book" violates check constraint "book_format_check" Detail: Failing row contains (1, Dune, AUDIOBOOK, null, fiction, 2026...
+ [RED] BookRepositoryTest.topRatedComesBestFirstAndUnratedBooksLast
+ Expecting actual: ["No Reviews Yet", "Dune", "Hamlet"] to contain exactly (and in same order):
+ ...
+ BookRepositoryTest PostgreSQL 17.12 jdbc:postgresql://localhost:54728/test?loggerLevel=OFF
+ ...
+RESULT: BROKEN, AND YOUR TESTS SEE IT. 2 of 8 tests fail, and 4 of 4 features are broken on Postgres.
+```
+
+The same two tests, unchanged, now fail with the same errors as production. That is the whole point:
+your test now runs where your bug lives.
+
+### Step 3: fix the code
+
+In `BookRepository`, put the unrated books last, and add a tie-breaker so equal ratings always come
+back in the same order:
+
+```java
+@Query("select b from Book b order by b.rating desc nulls last, b.id")
+List findTopRated(Limit limit);
+```
+
+(`where b.rating is not null` would also be correct: an unrated book is not "top rated". Either
+passes the checks.)
+
+Then add the migration the enum change needed. Create
+`src/main/resources/db/migration/V2__allow_audiobooks.sql`:
+
+```sql
+alter table book drop constraint book_format_check;
+alter table book add constraint book_format_check
+ check (format in ('PAPERBACK', 'HARDCOVER', 'EBOOK', 'AUDIOBOOK'));
+```
+
+Never edit `V1`: it has already run in production, and Flyway would refuse to start because its
+checksum changed. Schema changes are new migrations.
+
+### After
+
+```bash
+./check 2
+```
+
+```
+Task 2: Run the repository tests on Postgres, fix what they find
+ [PASS] Production: an AUDIOBOOK can be added (on Postgres, with the Flyway migrations)
+ [PASS] Production: top rated lists the best rated books first, and never an unrated book ahead of a rated one (on Postgres)
+ [PASS] Your suite: BookRepositoryTest runs on PostgreSQL, not H2
+ [PASS] Your suite: BookRepositoryTest's schema comes from the Flyway migrations, not from Hibernate
+ [PASS] Your suite: catches the missing migration (a test fails when the database rejects AUDIOBOOK)
+ [PASS] Your suite: catches the top rated bug (a test fails when findTopRated has no NULLS LAST)
+ 6 of 6 pass
+```
+
+The last two are the interesting ones. The check put the `start/` query back (and, separately,
+made the database reject `AUDIOBOOK` again) and ran your suite: a test turned red each time. In
+`start/` the same checks failed, because the H2 tests stayed green with the bugs in.
+
+`./demo` now says `[OK]` for "Top rated" and "Add an audiobook", and
+`RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. 8 of 8 tests pass, and 2 of 4 features are broken on Postgres.`
+Two to go.
+
+---
+
+## Task 3: Inspect Which Database Your Test Really Used
+
+### Step 1: what ran where
+
+```bash
+./inspect
+```
+
+```
+DATABASE EACH TEST CLASS USED
+ test class database url
+ ----------------------- ---------------- ------------------------------------------------------
+ BookRepositoryTest PostgreSQL 17.12 jdbc:postgresql://localhost:55721/test?loggerLevel=OFF
+ CatalogueApiTest H2 2.4.240 jdbc:h2:mem:catalogue
+ ShelfTest H2 2.4.240 jdbc:h2:mem:bc0099e2-2a6e-46c8-97c3-07ab8d6f12ef
+ SubscriptionServiceTest none no Spring context: a plain unit test
+
+WHERE EACH SCHEMA CAME FROM
+ context 1: Flyway migrations V1 create catalogue, V2 allow audiobooks
+ context 2: unknown: the context was closed (@DirtiesContext), its database with it
+ context 3: made up by Hibernate from the entities (no flyway_schema_history table)
+```
+
+`BookRepositoryTest` now has the real schema, both migrations. `ShelfTest` still runs on a schema
+Hibernate made up.
+
+### Step 2: who chose H2?
+
+`ShelfTest`'s URL is `jdbc:h2:mem:`. Nobody wrote that. `application.properties` says
+`jdbc:postgresql://localhost:5456/shop`. **`@DataJpaTest` replaced it.**
+
+`@DataJpaTest` includes `@AutoConfigureTestDatabase`. In Spring Boot 4 its default is
+`replace = NON_TEST`: if an embedded database (H2, HSQLDB, Derby) is on the test classpath, it swaps
+your DataSource for a fresh in-memory one, **unless** the DataSource is clearly a test database:
+
+```bash
+./check 3
+```
+
+```
+Task 3: Inspect what @DataJpaTest does with your database
+ [PASS] @DataJpaTest: a datasource URL from application.properties is swapped for an embedded H2
+ [PASS] @DataJpaTest: a @ServiceConnection container is kept, with no extra annotation: the test runs on Postgres
+ [PASS] @DataJpaTest: with @AutoConfigureTestDatabase(replace = NONE) the same URL is kept: the test runs on Postgres
+ 3 of 3 pass
+```
+
+| The URL comes from | `@DataJpaTest` does |
+|---|---|
+| `application.properties`, or `@DataJpaTest(properties = ...)` | Replaces it with an embedded H2 |
+| A `@ServiceConnection` container | Keeps it |
+| A `@DynamicPropertySource` method | Keeps it |
+| Anything, with `@AutoConfigureTestDatabase(replace = NONE)` (or `spring.test.database.replace=none`) | Keeps it |
+
+Spring Boot 3.3 and older replaced it whatever its source, which is why most Testcontainers
+examples online carry `@AutoConfigureTestDatabase(replace = NONE)`.
+
+### Step 3: break it on purpose
+
+In `BookRepositoryTest`, comment out `@ServiceConnection` (keep the container and the static block)
+and run `./inspect`:
+
+```
+ [FAIL] BookRepositoryTest.savesAnAudiobook
+ Unknown data type: "TIMESTAMPTZ"; SQL statement: create table book ( id bigint generated by default as identity primary key,
+ ...
+ BookRepositoryTest none its Spring context did not start (see the failure above)
+```
+
+The container started, but Spring no longer knew about it. The URL came from
+`application.properties`, so `@DataJpaTest` swapped in an embedded H2, and Flyway ran the real
+migration on it. H2 does not even know Postgres's `timestamptz` type. **Put `@ServiceConnection`
+back.**
+
+### Step 4: what a slice loads
+
+| | `@DataJpaTest` | `@SpringBootTest` |
+|---|---|---|
+| Loads | JPA, repositories, the DataSource, Flyway | The whole application |
+| Web layer | No | Yes, a real server with `RANDOM_PORT` |
+| Transactions | Every test in one, rolled back at the end | Only what your code opens |
+| Use it for | Queries, mappings, constraints, migrations | A request through every layer |
+
+### What to take away
+
+- Always check which database a test really used. `./inspect` here; in a real project, log or assert
+ `connection.getMetaData().getURL()` once.
+- `@DataJpaTest` replaces a DataSource it does not recognise as a test database. A
+ `@ServiceConnection` container is recognised.
+
+---
+
+## Task 4: Replace the Fake Where It Hides the SQL
+
+### Step 1: test the SQL itself
+
+Create `src/test/java/com/amigoscode/realdb/subscription/SubscriberRepositoryTest.java`:
+
+```java
+package com.amigoscode.realdb.subscription;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
+import org.testcontainers.postgresql.PostgreSQLContainer;
+
+@DataJpaTest
+class SubscriberRepositoryTest {
+
+ @ServiceConnection
+ static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine");
+
+ static {
+ POSTGRES.start();
+ }
+
+ @Autowired
+ SubscriberRepository subscribers;
+
+ @Test
+ void subscribesANewAddress() {
+ assertThat(subscribers.subscribe("ann@example.com")).isEqualTo(1);
+ assertThat(subscribers.count()).isEqualTo(1);
+ }
+
+ @Test
+ void theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce() {
+ assertThat(subscribers.subscribe("ann@example.com")).isEqualTo(1);
+ assertThat(subscribers.subscribe("Ann@Example.COM")).isEqualTo(0);
+
+ assertThat(subscribers.count()).isEqualTo(1);
+ }
+}
+```
+
+The container lines are copied from `BookRepositoryTest`. Leave them for now: Task 5 deals with that.
+
+```bash
+./demo
+```
+
+```
+ [RED] SubscriberRepositoryTest.subscribesANewAddress
+ ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
+ [RED] SubscriberRepositoryTest.theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce
+ ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
+ [GREEN] SubscriptionServiceTest.aNewAddressIsSubscribed
+ [GREEN] SubscriptionServiceTest.rejectsSomethingThatIsNotAnEmailAddress
+ [GREEN] SubscriptionServiceTest.theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce
+```
+
+Even the very first subscribe fails. The fake test right below says the same feature works.
+
+### Why
+
+`V1__create_catalogue.sql` makes addresses unique ignoring case:
+
+```sql
+create unique index subscriber_email_key on subscriber (lower(email));
+```
+
+`ON CONFLICT (email)` asks Postgres for a unique index on the column `email`. There is none: the
+index is on the expression `lower(email)`. Postgres checks this before it inserts anything, so the
+statement fails every time. The fake lower-cases the address in Java and never runs SQL, so it
+"works". H2 cannot parse the statement at all, which is why the fake was written in the first place.
+
+### Step 2: fix the SQL
+
+In `SubscriberRepository.subscribe`, name the expression the index is built on:
+
+```java
+@Query(value = """
+ insert into subscriber (email) values (:email)
+ on conflict (lower(email)) do nothing
+ """, nativeQuery = true)
+int subscribe(@Param("email") String email);
+```
+
+### Step 3: keep the fake, for what it is good at
+
+The fake is not wrong. It is the right tool for the service's own logic: the email check, and "0
+rows means ALREADY_SUBSCRIBED". Those tests run in milliseconds without Spring or Docker. Rename the
+one that pretends to be about SQL, so it says what it really tests: in `SubscriptionServiceTest`,
+rename `theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce` to
+`whenTheRepositoryAddsNothingTheAddressWasAlreadySubscribed`.
+
+| Fake or mock is fine | Needs the real database |
+|---|---|
+| Decisions in the service: validation, mapping, what a result means | Every query you wrote, native or JPQL |
+| Calls to other services | Constraints, indexes, `ON CONFLICT`, migrations |
+| Error handling paths | Transactions, locks, isolation |
+
+### After
+
+```bash
+./check 4
+```
+
+```
+Task 4: Replace the fake where it hides the SQL
+ [PASS] Production: subscribing ann@example.com, then Ann@Example.COM, keeps one subscriber and answers ALREADY_SUBSCRIBED (on Postgres)
+ [PASS] Your suite: SubscriptionServiceTest still tests the service's logic with the fake, with no Spring and no database
+ [PASS] Your suite: catches the ON CONFLICT bug (a test fails when subscribe uses ON CONFLICT (email))
+ 3 of 3 pass
+```
+
+---
+
+## Task 5: One Container, One Context per Kind of Test
+
+### Step 1: count
+
+```bash
+./inspect
+```
+
+```
+POSTGRES SERVERS (one per container): 2
+ server id started at used by contexts
+ ------------------- ------------ ----------------
+ 7714810932418117666 20:46:35.912 1
+ 7714810951974785058 20:46:40.440 4
+
+SPRING CONTEXTS STARTED: 4
+ # kind start-up used by
+ - --------------- -------- ------------------------
+ 1 @DataJpaTest 2,109 ms BookRepositoryTest
+ 2 @SpringBootTest 745 ms CatalogueApiTest
+ 3 @DataJpaTest 115 ms ShelfTest
+ 4 @DataJpaTest 252 ms SubscriberRepositoryTest
+```
+
+Two containers, because two classes each declare their own. Four contexts for two kinds of test.
+
+**Spring's test context cache.** Spring keeps every context it starts in a cache, keyed by the test
+class's whole configuration: the slice, `properties`, `@Import`, `@ActiveProfiles`,
+`@MockitoBean`/`@MockitoSpyBean` fields, `@DynamicPropertySource` methods, `@ServiceConnection`
+fields. Two classes with exactly the same configuration share one context. Here every class is
+different:
+
+- `BookRepositoryTest` and `SubscriberRepositoryTest` each declare **their own** container field.
+- `ShelfTest` has `properties = {... "spring.jpa.properties.hibernate.format_sql=true"}`, left over
+ from debugging. One harmless property, one more context.
+- `CatalogueApiTest` has `@DirtiesContext`, which closes its context after the class. The next class
+ that needs one starts it again. It does nothing to the rows in a database container.
+
+With 4 test classes the cost is seconds. With 200 test classes it is the difference between 1 and
+15 minutes.
+
+### Step 2: one base class
+
+Create `src/test/java/com/amigoscode/realdb/support/PostgresTest.java`:
+
+```java
+package com.amigoscode.realdb.support;
+
+import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
+import org.testcontainers.postgresql.PostgreSQLContainer;
+
+/** One Postgres for the whole test run. Every test class that needs a database extends this class. */
+public abstract class PostgresTest {
+
+ @ServiceConnection
+ static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine");
+
+ static {
+ POSTGRES.start();
+ }
+}
+```
+
+A static field is created once per JVM, however many classes extend it. It is not stopped after
+each class: Testcontainers removes it when the JVM ends.
+
+> **Why not `@Testcontainers` and `@Container`?** That JUnit extension starts the container before
+> each test class and stops it after. With Spring's context cache it is worse than slow: the next run
+> of the same configuration gets a cached context that still points at the stopped container's old
+> port, and usually fails with `Connection refused` (the checks run your suite several times in one
+> JVM). Use `@Container` only for a container that belongs to one class and has no cached context.
+
+### Step 3: every database test extends it
+
+- `BookRepositoryTest` and `SubscriberRepositoryTest`: delete the container field, the static block
+ and their two imports; add `extends PostgresTest` and import
+ `com.amigoscode.realdb.support.PostgresTest`.
+- `ShelfTest`: replace its whole `@DataJpaTest(properties = {...})` with `@DataJpaTest`, and
+ `extends PostgresTest`.
+- `CatalogueApiTest`: replace the `@SpringBootTest(...)` with
+ `@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)`, delete
+ `@DirtiesContext` and its import, and `extends PostgresTest`. Leave `@Transactional` and the
+ `@Order`s for Task 6.
+
+### Step 4: count again
+
+```bash
+./inspect
+```
+
+```
+ [FAIL] CatalogueApiTest.addsABook
+ expected: 1L but was: 6L
+ [PASS] CatalogueApiTest.listsTheShelf
+ [FAIL] ShelfTest.shelfListsBooksInTheOrderTheyWereAdded
+ Expecting actual: ["Beloved", "Beloved", "Middlemarch", "Rebecca"] to contain exactly (and in same order): ["Beloved", "Middlemarch", "Rebecca"]
+...
+POSTGRES SERVERS (one per container): 1
+ server id started at used by contexts
+ ------------------- ------------ ----------------
+ 7714812563007639585 20:52:58.139 1, 2
+
+SPRING CONTEXTS STARTED: 2
+ # kind start-up used by
+ - --------------- -------- -------------------------------------------------------
+ 1 @DataJpaTest 5,441 ms BookRepositoryTest, ShelfTest, SubscriberRepositoryTest
+ 2 @SpringBootTest 1,947 ms CatalogueApiTest
+```
+
+One server, two contexts: one per kind of test. That is the floor: a `@DataJpaTest` and a
+`@SpringBootTest` are different configurations and can never share. (Your start-up times will
+differ; that is why the checks count contexts and never measure time.)
+
+```bash
+./check 5
+```
+
+```
+Task 5: One container, one context per kind of test
+ [PASS] Your suite: at most 2 Spring contexts, one per kind of test (@DataJpaTest, @SpringBootTest)
+ [PASS] Your suite: every Spring test runs on PostgreSQL (no H2 left)
+ [PASS] Your suite: one Postgres container for the whole run, shared by every test class
+ 3 of 3 pass
+```
+
+Two tests went red. On H2, every class had a database of its own, so tests could not see each
+other. Now they share one, and they do. That is Task 6.
+
+> **Testcontainers reuse.** With `.withReuse(true)` on the container and
+> `testcontainers.reuse.enable=true` in `~/.testcontainers.properties`, Testcontainers leaves the
+> container running after the JVM ends and the next run attaches to it: no start-up at all. It is a
+> local convenience. The data survives between runs too, nothing removes the container for you, and
+> CI should always start fresh.
+
+---
+
+## Task 6: Tests That Own Their Data
+
+### Step 1: what failed, and why
+
+```bash
+./check 6
+```
+
+```
+Task 6: Tests that own their data
+ [FAIL] Your suite: every test gives the same result with classes and methods run from Z to A
+ The order changes the result. Some test leaves data behind that another one trips over:
+ CatalogueApiTest.listsTheShelf passes A to Z, fails Z to A: Expecting actual: ["Beloved", "Beloved"] to contain exactly (and in same order): ["Beloved"]
+ [FAIL] Your suite: every test that passes in the full run also passes when it runs on its own
+ ...
+ 0 of 3 pass
+```
+
+Three problems, all from sharing a database:
+
+- **`addsABook` expects id 1 and gets 6.** `BookRepositoryTest` ran first. Its inserts were rolled
+ back, but **sequences are never rolled back**: ids 1 to 5 are used up for good.
+- **`listsTheShelf` needs `addsABook`** to have run first (`@Order(2)`) and left "Beloved" behind.
+- **`ShelfTest` finds two "Beloved"s.** `@DataJpaTest` rolls back *its own* test. It cannot remove
+ the row `CatalogueApiTest` committed before it.
+
+### Step 2: the obvious fix, and the trap
+
+Make `listsTheShelf` create its own books. The class is `@Transactional`, so they will be rolled
+back. In `CatalogueApiTest`:
+
+```java
+@Autowired
+BookRepository books;
+
+@Test
+@Order(2)
+void listsTheShelf() {
+ books.save(new Book("Beloved", Format.PAPERBACK, "fiction"));
+ books.save(new Book("Middlemarch", Format.HARDCOVER, "fiction"));
+
+ List shelf = http.get().uri("/api/shelves/fiction").retrieve()
+ .body(new ParameterizedTypeReference<>() { });
+
+ assertThat(shelf).extracting(BookView::title).containsExactly("Beloved", "Middlemarch");
+}
+```
+
+```bash
+./demo
+```
+
+```
+ [RED] CatalogueApiTest.listsTheShelf
+ Expecting actual: ["Beloved"] to contain exactly (and in same order): ["Beloved", "Middlemarch"]
+```
+
+The server returned **one** book: the "Beloved" that `addsABook` committed. The two books this test
+saved are invisible.
+
+`@Transactional` on a test opens a transaction **on the test's thread**. `books.save` ran inside it,
+uncommitted. The HTTP request is handled by the server on **another thread**, in **its own**
+transaction, which cannot see uncommitted rows. And the other way round: everything the server
+writes, it commits, and the test's rollback does not touch it.
+
+The same is true for anything that leaves the test's thread or transaction: an `@Async` method, a
+`@Transactional(propagation = REQUIRES_NEW)` method, a message listener. A rolled back test only
+cleans up what ran in its own transaction.
+
+### Step 3: the fix
+
+Every test starts from empty tables, whatever ran before it. In `PostgresTest`:
+
+```java
+@Autowired
+private DataSource dataSource;
+
+/** Every test starts from empty tables, whatever ran before it. */
+@BeforeEach
+void startFromEmptyTables() {
+ new JdbcTemplate(dataSource).execute("truncate table book, subscriber");
+}
+```
+
+Imports: `javax.sql.DataSource`, `org.junit.jupiter.api.BeforeEach`,
+`org.springframework.beans.factory.annotation.Autowired`, `org.springframework.jdbc.core.JdbcTemplate`.
+
+Clean **before** each test, not after: then no test depends on the previous one having tidied up, and
+after a failure the rows are still there to look at. In a `@DataJpaTest` the truncate runs inside the
+test's transaction, so it is rolled back with the rest, which is fine: that test only needs empty
+tables while it runs. No `restart identity`: ids keep counting up, so no test can rely on them.
+
+Then replace the body of `CatalogueApiTest` from the annotations to the end of `listsTheShelf`: no
+`@Transactional`, no order, every test adds its own books over HTTP, and the id comes from the
+response:
+
+```java
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class CatalogueApiTest extends PostgresTest {
+
+ @LocalServerPort
+ int port;
+
+ RestClient http;
+
+ @BeforeEach
+ void client() {
+ http = RestClient.create("http://localhost:" + port);
+ }
+
+ @Test
+ void addsABook() {
+ ResponseEntity response = add("Beloved", "fiction");
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
+ long id = response.getBody().id();
+ assertThat(response.getHeaders().getLocation()).hasToString("/api/books/" + id);
+ }
+
+ @Test
+ void listsTheShelf() {
+ add("Beloved", "fiction");
+ add("Middlemarch", "fiction");
+ add("Ariel", "poetry");
+
+ List shelf = http.get().uri("/api/shelves/fiction").retrieve()
+ .body(new ParameterizedTypeReference<>() { });
+
+ assertThat(shelf).extracting(BookView::title).containsExactly("Beloved", "Middlemarch");
+ }
+```
+
+Keep the `add` helper. Remove the imports that are no longer used (`MethodOrderer`, `Order`,
+`TestMethodOrder`, `Transactional`, `Autowired`).
+
+### After
+
+```bash
+./check 6
+```
+
+```
+Task 6: Tests that own their data
+ [PASS] Your suite: every test gives the same result with classes and methods run from Z to A
+ [PASS] Your suite: every test that passes in the full run also passes when it runs on its own
+ [PASS] Your suite: no test depends on the value of a generated id (every sequence moved on by 1000 before each test)
+ 3 of 3 pass
+```
+
+The last check moved every id sequence on by 1000 just before each test body. In `start/` it failed
+on `addsABook` with `expected: 1L but was: 1005000L`. On H2 the test only passed because
+`@DirtiesContext` gave it a brand new database every time.
+
+---
+
+## Task 7: Order You Can Rely On
+
+### Step 1: make the test able to fail
+
+`ShelfTest` passes on Postgres. Run `./check 7`:
+
+```
+ [FAIL] Your suite: catches the missing ORDER BY (a test fails when findByShelf has no ORDER BY)
+ Your suite ran with the start/ version of findByShelf put back, and no test that passes now failed.
+ So it would not catch this bug. On Postgres, update one of the books (rate it) before you read the shelf, and assert on the order.
+```
+
+It passes by luck. Freshly inserted rows usually come back in insertion order, with or without
+`ORDER BY`. Production rates books. In `ShelfTest`, keep the first book in a variable and rate it
+before reading the shelf:
+
+```java
+Book beloved = books.save(new Book("Beloved", Format.PAPERBACK, "fiction"));
+books.save(new Book("Middlemarch", Format.HARDCOVER, "fiction"));
+books.save(new Book("Rebecca", Format.EBOOK, "fiction"));
+books.save(new Book("Ariel", Format.PAPERBACK, "poetry"));
+
+beloved.rate(new BigDecimal("4.5"));
+```
+
+(Import `java.math.BigDecimal`.) `./demo`:
+
+```
+ [RED] ShelfTest.shelfListsBooksInTheOrderTheyWereAdded
+ Expecting actual: ["Middlemarch", "Rebecca", "Beloved"] to contain exactly (and in same order): ["Beloved", "Middlemarch", "Rebecca"]
+```
+
+### Why
+
+Postgres never changes a row in place. An UPDATE writes a **new version** of the row in free space,
+usually after the existing rows, and marks the old one dead. A query without `ORDER BY` reads the
+table front to back, so the book you just rated comes back last. H2 keeps rows in primary key order,
+so on H2 the same test cannot fail. SQL makes no promise about order without `ORDER BY`. Neither
+database is wrong; the query is.
+
+### Step 2: fix the query
+
+In `BookRepository`:
+
+```java
+/** The books on one shelf, in the order they were added. */
+@Query("select b from Book b where b.shelf = :shelf order by b.addedAt, b.id")
+List findByShelf(@Param("shelf") String shelf);
+```
+
+Import `org.springframework.data.repository.query.Param`. `b.id` breaks ties when two books share a
+timestamp. (A derived name like `findByShelfOrderByAddedAtAscIdAsc` would also work, but the checks
+call `findByShelf`, so keep the name.)
+
+### After
+
+```bash
+./check 7
+./check
+```
+
+```
+Task 7: Order you can rely on
+ [PASS] Production: a shelf lists its books in the order they were added, also after one of them is updated (on Postgres)
+ [PASS] Your suite: catches the missing ORDER BY (a test fails when findByShelf has no ORDER BY)
+ 2 of 2 pass
+```
+
+`./check` should now print 24 passes and no failures.
+
+Two rules about tests and order:
+
+- If the order is part of the contract, the query has an `ORDER BY`, and the test does something
+ (an update, a delete) that would break the order without it.
+- If the order is not part of the contract, the test says so: `containsExactlyInAnyOrder`, not
+ `containsExactly`. Asserting an order nobody promised is a test that fails one day for no reason.
+
+---
+
+## Task 8: Compare, and the Test Pyramid
+
+### Step 1: the same demo, again
+
+```bash
+./demo
+```
+
+```
+ BookRepositoryTest PostgreSQL 17.12 jdbc:postgresql://localhost:64204/test?loggerLevel=OFF
+ CatalogueApiTest PostgreSQL 17.12 jdbc:postgresql://localhost:64204/test?loggerLevel=OFF
+ ...
+ SubscriptionServiceTest none no Spring context: a plain unit test
+ ...
+RESULT: OK. All 10 tests pass, and all 4 features work on Postgres.
+```
+
+One URL for every database test: one container. The fake test still needs nothing. Compare with
+Task 1: the same features, the same kind of tests, and now they would have told you.
+
+### Step 2: what is left behind
+
+```bash
+./inspect
+```
+
+```
+SPRING CONTEXTS STARTED: 2
+ # kind start-up used by
+ - --------------- -------- -------------------------------------------------------
+ 1 @DataJpaTest 2,362 ms BookRepositoryTest, ShelfTest, SubscriberRepositoryTest
+ 2 @SpringBootTest 854 ms CatalogueApiTest
+
+ROWS LEFT BEHIND AFTER THE LAST TEST
+ context database book subscriber
+ ------- ---------------- ---- ----------
+ 1 PostgreSQL 17.12 3 0
+ 2 PostgreSQL 17.12 3 0
+```
+
+Both contexts point at the same database. The 3 books are `CatalogueApiTest.listsTheShelf`'s: it
+committed them over HTTP. The `@DataJpaTest` classes that ran after it truncated the tables inside
+their own transactions, and those were rolled back. Leftovers are fine, because every test cleans
+**before** it starts.
+
+### Step 3: the test pyramid for a Spring service
+
+| Layer | What | How many | Tools here | Needs |
+|---|---|---|---|---|
+| Unit | Logic in services, mappers, validators | Most | JUnit, a fake (`SubscriptionServiceTest`) | Nothing. Milliseconds |
+| Data access | Queries, mappings, constraints, migrations, transactions | One per query and rule | `@DataJpaTest` + Testcontainers | Docker. Seconds to start, then fast |
+| End to end | A request through every layer | A few | `@SpringBootTest(RANDOM_PORT)` + Testcontainers | Docker |
+
+**Docker in CI.** GitHub Actions Linux runners, GitLab with a Docker service and most CI systems
+have it. If yours does not, look for a remote Docker host or Testcontainers Cloud before you give up
+on real databases; do not quietly switch to H2 in CI.
+
+**When an in-memory database is acceptable:** when the code does not depend on the database. A
+prototype with plain CRUD, or a library that must run on several databases and is tested on each.
+Not when production runs on Postgres and the code uses its SQL, types or constraints.
+
+### How to say it in an interview
+
+> "I test logic with plain unit tests, with a hand-written fake where the service needs a repository.
+> Everything that talks to the database I test against the same database as production, with
+> Testcontainers and the real Flyway migrations, because H2 behaves differently: it sorts NULLs
+> differently, returns rows in a different order, and cannot run our migrations or our ON CONFLICT
+> queries. A fake or a mock of the repository proves nothing about the SQL. To keep it fast I start
+> one container per test run, a static field in a base class with @ServiceConnection, and keep the
+> test configuration identical so Spring's context cache reuses contexts: no @DirtiesContext, no
+> one-off properties or @MockitoBeans. Every test owns its data: it truncates the tables before it
+> starts, never assumes an id, and I don't put @Transactional on tests that go through HTTP, because
+> the server commits in its own transaction."
+
+Then be ready for the follow-ups in "Questions to Ask Afterwards" at the end of
+[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md).
+
+---
+
+## Clean up
+
+```bash
+docker compose down -v
+```
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/jvm.config b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/jvm.config
new file mode 100644
index 0000000..07a2d88
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/jvm.config
@@ -0,0 +1,2 @@
+--enable-native-access=ALL-UNNAMED
+--sun-misc-unsafe-memory-access=allow
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ffcab66
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,3 @@
+wrapperVersion=3.3.4
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check
new file mode 100755
index 0000000..790e98e
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use check.cmd (type: .\check).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.realdb.check.Check -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check.cmd
new file mode 100644
index 0000000..eed036c
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./check
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.realdb.check.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/compose.yaml b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/compose.yaml
new file mode 100644
index 0000000..2d3ffc3
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/compose.yaml
@@ -0,0 +1,16 @@
+name: testing-with-a-real-database
+services:
+ postgres:
+ image: postgres:17-alpine
+ container_name: testing-with-a-real-database-postgres
+ environment:
+ POSTGRES_DB: shop
+ POSTGRES_USER: shop
+ POSTGRES_PASSWORD: shop
+ ports:
+ - "5456:5432"
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U shop -d shop"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo
new file mode 100755
index 0000000..402789c
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.realdb.check.Demo -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo.cmd
new file mode 100644
index 0000000..1b65591
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./demo
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.realdb.check.Demo" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect
new file mode 100755
index 0000000..10bb2f9
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.realdb.check.Inspect -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect.cmd
new file mode 100644
index 0000000..99f2d61
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./inspect
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.realdb.check.Inspect" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw
new file mode 100755
index 0000000..bd8896b
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw
@@ -0,0 +1,295 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Apache Maven Wrapper startup batch script, version 3.3.4
+#
+# Optional ENV vars
+# -----------------
+# JAVA_HOME - location of a JDK home dir, required when download maven via java source
+# MVNW_REPOURL - repo url base for downloading maven distribution
+# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
+# ----------------------------------------------------------------------------
+
+set -euf
+[ "${MVNW_VERBOSE-}" != debug ] || set -x
+
+# OS specific support.
+native_path() { printf %s\\n "$1"; }
+case "$(uname)" in
+CYGWIN* | MINGW*)
+ [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
+ native_path() { cygpath --path --windows "$1"; }
+ ;;
+esac
+
+# set JAVACMD and JAVACCMD
+set_java_home() {
+ # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
+ if [ -n "${JAVA_HOME-}" ]; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ]; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ JAVACCMD="$JAVA_HOME/jre/sh/javac"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ JAVACCMD="$JAVA_HOME/bin/javac"
+
+ if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
+ echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
+ echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
+ return 1
+ fi
+ fi
+ else
+ JAVACMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v java
+ )" || :
+ JAVACCMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v javac
+ )" || :
+
+ if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
+ echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
+ return 1
+ fi
+ fi
+}
+
+# hash string like Java String::hashCode
+hash_string() {
+ str="${1:-}" h=0
+ while [ -n "$str" ]; do
+ char="${str%"${str#?}"}"
+ h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
+ str="${str#?}"
+ done
+ printf %x\\n $h
+}
+
+verbose() { :; }
+[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
+
+die() {
+ printf %s\\n "$1" >&2
+ exit 1
+}
+
+trim() {
+ # MWRAPPER-139:
+ # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
+ # Needed for removing poorly interpreted newline sequences when running in more
+ # exotic environments such as mingw bash on Windows.
+ printf "%s" "${1}" | tr -d '[:space:]'
+}
+
+scriptDir="$(dirname "$0")"
+scriptName="$(basename "$0")"
+
+# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
+while IFS="=" read -r key value; do
+ case "${key-}" in
+ distributionUrl) distributionUrl=$(trim "${value-}") ;;
+ distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
+ esac
+done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+
+case "${distributionUrl##*/}" in
+maven-mvnd-*bin.*)
+ MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
+ case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
+ *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
+ :Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
+ :Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
+ :Linux*x86_64*) distributionPlatform=linux-amd64 ;;
+ *)
+ echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
+ distributionPlatform=linux-amd64
+ ;;
+ esac
+ distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
+ ;;
+maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
+*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
+esac
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
+[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
+distributionUrlName="${distributionUrl##*/}"
+distributionUrlNameMain="${distributionUrlName%.*}"
+distributionUrlNameMain="${distributionUrlNameMain%-bin}"
+MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
+MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
+
+exec_maven() {
+ unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
+ exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
+}
+
+if [ -d "$MAVEN_HOME" ]; then
+ verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ exec_maven "$@"
+fi
+
+case "${distributionUrl-}" in
+*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
+*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
+esac
+
+# prepare tmp dir
+if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
+ clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
+ trap clean HUP INT TERM EXIT
+else
+ die "cannot create temp dir"
+fi
+
+mkdir -p -- "${MAVEN_HOME%/*}"
+
+# Download and Install Apache Maven
+verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+verbose "Downloading from: $distributionUrl"
+verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+# select .zip or .tar.gz
+if ! command -v unzip >/dev/null; then
+ distributionUrl="${distributionUrl%.zip}.tar.gz"
+ distributionUrlName="${distributionUrl##*/}"
+fi
+
+# verbose opt
+__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
+[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
+
+# normalize http auth
+case "${MVNW_PASSWORD:+has-password}" in
+'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+esac
+
+if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
+ verbose "Found wget ... using wget"
+ wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
+elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
+ verbose "Found curl ... using curl"
+ curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
+elif set_java_home; then
+ verbose "Falling back to use Java to download"
+ javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
+ targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
+ cat >"$javaSource" <<-END
+ public class Downloader extends java.net.Authenticator
+ {
+ protected java.net.PasswordAuthentication getPasswordAuthentication()
+ {
+ return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
+ }
+ public static void main( String[] args ) throws Exception
+ {
+ setDefault( new Downloader() );
+ java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
+ }
+ }
+ END
+ # For Cygwin/MinGW, switch paths to Windows format before running javac and java
+ verbose " - Compiling Downloader.java ..."
+ "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
+ verbose " - Running Downloader.java ..."
+ "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
+fi
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+if [ -n "${distributionSha256Sum-}" ]; then
+ distributionSha256Result=false
+ if [ "$MVN_CMD" = mvnd.sh ]; then
+ echo "Checksum validation is not supported for maven-mvnd." >&2
+ echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ elif command -v sha256sum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ elif command -v shasum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ else
+ echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
+ echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ fi
+ if [ $distributionSha256Result = false ]; then
+ echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
+ echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
+ exit 1
+ fi
+fi
+
+# unzip and move
+if command -v unzip >/dev/null; then
+ unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
+else
+ tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
+fi
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+actualDistributionDir=""
+
+# First try the expected directory name (for regular distributions)
+if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
+ if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$distributionUrlNameMain"
+ fi
+fi
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if [ -z "$actualDistributionDir" ]; then
+ # enable globbing to iterate over items
+ set +f
+ for dir in "$TMP_DOWNLOAD_DIR"/*; do
+ if [ -d "$dir" ]; then
+ if [ -f "$dir/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$(basename "$dir")"
+ break
+ fi
+ fi
+ done
+ set -f
+fi
+
+if [ -z "$actualDistributionDir" ]; then
+ verbose "Contents of $TMP_DOWNLOAD_DIR:"
+ verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
+ die "Could not find Maven distribution directory in extracted archive"
+fi
+
+verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw.cmd
new file mode 100644
index 0000000..92450f9
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw.cmd
@@ -0,0 +1,189 @@
+<# : batch portion
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Apache Maven Wrapper startup batch script, version 3.3.4
+@REM
+@REM Optional ENV vars
+@REM MVNW_REPOURL - repo url base for downloading maven distribution
+@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
+@REM ----------------------------------------------------------------------------
+
+@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
+@SET __MVNW_CMD__=
+@SET __MVNW_ERROR__=
+@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
+@SET PSModulePath=
+@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
+ IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
+)
+@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
+@SET __MVNW_PSMODULEP_SAVE=
+@SET __MVNW_ARG0_NAME__=
+@SET MVNW_USERNAME=
+@SET MVNW_PASSWORD=
+@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
+@echo Cannot start maven from wrapper >&2 && exit /b 1
+@GOTO :EOF
+: end batch / begin powershell #>
+
+$ErrorActionPreference = "Stop"
+if ($env:MVNW_VERBOSE -eq "true") {
+ $VerbosePreference = "Continue"
+}
+
+# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
+$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
+if (!$distributionUrl) {
+ Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+}
+
+switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
+ "maven-mvnd-*" {
+ $USE_MVND = $true
+ $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
+ $MVN_CMD = "mvnd.cmd"
+ break
+ }
+ default {
+ $USE_MVND = $false
+ $MVN_CMD = $script -replace '^mvnw','mvn'
+ break
+ }
+}
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
+if ($env:MVNW_REPOURL) {
+ $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
+ $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
+}
+$distributionUrlName = $distributionUrl -replace '^.*/',''
+$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
+
+$MAVEN_M2_PATH = "$HOME/.m2"
+if ($env:MAVEN_USER_HOME) {
+ $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
+}
+
+if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
+ New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
+}
+
+$MAVEN_WRAPPER_DISTS = $null
+if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
+ $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
+} else {
+ $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
+}
+
+$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
+$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
+
+if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
+ Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+ exit $?
+}
+
+if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
+ Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
+}
+
+# prepare tmp dir
+$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
+$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
+$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
+trap {
+ if ($TMP_DOWNLOAD_DIR.Exists) {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+ }
+}
+
+New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
+
+# Download and Install Apache Maven
+Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+Write-Verbose "Downloading from: $distributionUrl"
+Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+$webclient = New-Object System.Net.WebClient
+if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
+ $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
+}
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
+if ($distributionSha256Sum) {
+ if ($USE_MVND) {
+ Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
+ }
+ Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
+ if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
+ Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
+ }
+}
+
+# unzip and move
+Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+$actualDistributionDir = ""
+
+# First try the expected directory name (for regular distributions)
+$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
+$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
+if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
+ $actualDistributionDir = $distributionUrlNameMain
+}
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if (!$actualDistributionDir) {
+ Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
+ $testPath = Join-Path $_.FullName "bin/$MVN_CMD"
+ if (Test-Path -Path $testPath -PathType Leaf) {
+ $actualDistributionDir = $_.Name
+ }
+ }
+}
+
+if (!$actualDistributionDir) {
+ Write-Error "Could not find Maven distribution directory in extracted archive"
+}
+
+Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
+try {
+ Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
+} catch {
+ if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
+ Write-Error "fail to move MAVEN_HOME"
+ }
+} finally {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+}
+
+Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/pom.xml b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/pom.xml
new file mode 100644
index 0000000..0b7e35b
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/pom.xml
@@ -0,0 +1,134 @@
+
+
+ 4.0.0
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 4.0.2
+
+
+
+ com.amigoscode
+ testing-with-a-real-database
+ 0.0.1-SNAPSHOT
+ testing-with-a-real-database
+ Testing data access against a real Postgres with Testcontainers instead of H2 or mocks
+
+
+ 25
+ 3.5.0
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-webmvc
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+ org.springframework.boot
+ spring-boot-starter-flyway
+
+
+ org.flywaydb
+ flyway-database-postgresql
+
+
+ org.postgresql
+ postgresql
+ runtime
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.mockito
+ mockito-core
+
+
+ org.mockito
+ mockito-junit-jupiter
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa-test
+ test
+
+
+
+ org.springframework.boot
+ spring-boot-testcontainers
+ test
+
+
+ org.testcontainers
+ testcontainers-postgresql
+ test
+
+
+
+ org.testcontainers
+ testcontainers-junit-jupiter
+ test
+
+
+
+ com.h2database
+ h2
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+ false
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java
new file mode 100644
index 0000000..5a8f484
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java
@@ -0,0 +1,23 @@
+package com.amigoscode.realdb;
+
+import com.amigoscode.realdb.catalogue.BookNotFoundException;
+import com.amigoscode.realdb.subscription.InvalidEmailException;
+import java.util.Map;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class ApiExceptionHandler {
+
+ @ExceptionHandler(BookNotFoundException.class)
+ ResponseEntity> notFound(BookNotFoundException e) {
+ return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("code", "BOOK_NOT_FOUND", "message", e.getMessage()));
+ }
+
+ @ExceptionHandler(InvalidEmailException.class)
+ ResponseEntity> invalidEmail(InvalidEmailException e) {
+ return ResponseEntity.badRequest().body(Map.of("code", "INVALID_EMAIL", "message", e.getMessage()));
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java
new file mode 100644
index 0000000..f16f735
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java
@@ -0,0 +1,12 @@
+package com.amigoscode.realdb;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class RealDatabaseApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(RealDatabaseApplication.class, args);
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Book.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Book.java
new file mode 100644
index 0000000..da07ac2
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Book.java
@@ -0,0 +1,81 @@
+package com.amigoscode.realdb.catalogue;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.Enumerated;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import java.math.BigDecimal;
+import java.time.Instant;
+
+@Entity
+@Table(name = "book")
+public class Book {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @Column(nullable = false)
+ private String title;
+
+ @Enumerated(EnumType.STRING)
+ @Column(nullable = false, length = 20)
+ private Format format;
+
+ /** Average review score from 1.0 to 5.0. Null until the book has its first review. */
+ @Column(precision = 2, scale = 1)
+ private BigDecimal rating;
+
+ @Column(nullable = false)
+ private String shelf;
+
+ @Column(name = "added_at", nullable = false)
+ private Instant addedAt;
+
+ protected Book() {
+ }
+
+ public Book(String title, Format format, String shelf) {
+ this.title = title;
+ this.format = format;
+ this.shelf = shelf;
+ this.addedAt = Instant.now();
+ }
+
+ public void rate(BigDecimal rating) {
+ this.rating = rating;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public Format getFormat() {
+ return format;
+ }
+
+ public BigDecimal getRating() {
+ return rating;
+ }
+
+ public String getShelf() {
+ return shelf;
+ }
+
+ public Instant getAddedAt() {
+ return addedAt;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java
new file mode 100644
index 0000000..028d096
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java
@@ -0,0 +1,8 @@
+package com.amigoscode.realdb.catalogue;
+
+public class BookNotFoundException extends RuntimeException {
+
+ public BookNotFoundException(long id) {
+ super("No book with id " + id);
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java
new file mode 100644
index 0000000..4f6b5c2
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java
@@ -0,0 +1,19 @@
+package com.amigoscode.realdb.catalogue;
+
+import java.util.List;
+import org.springframework.data.domain.Limit;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+/** The acceptance checks call findTopRated and findByShelf by name: fix them, do not rename them. */
+public interface BookRepository extends JpaRepository {
+
+ /** The best rated books first. A book without a rating has no reviews yet: it goes last. */
+ @Query("select b from Book b order by b.rating desc nulls last, b.id")
+ List findTopRated(Limit limit);
+
+ /** The books on one shelf, in the order they were added. */
+ @Query("select b from Book b where b.shelf = :shelf order by b.addedAt, b.id")
+ List findByShelf(@Param("shelf") String shelf);
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java
new file mode 100644
index 0000000..ea4458d
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java
@@ -0,0 +1,58 @@
+package com.amigoscode.realdb.catalogue;
+
+import java.math.BigDecimal;
+import java.net.URI;
+import java.util.List;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api")
+public class CatalogueController {
+
+ public record NewBook(String title, Format format, String shelf) {
+ }
+
+ public record NewRating(BigDecimal rating) {
+ }
+
+ public record BookView(long id, String title, Format format, BigDecimal rating, String shelf) {
+
+ static BookView of(Book book) {
+ return new BookView(book.getId(), book.getTitle(), book.getFormat(), book.getRating(), book.getShelf());
+ }
+ }
+
+ private final CatalogueService catalogue;
+
+ public CatalogueController(CatalogueService catalogue) {
+ this.catalogue = catalogue;
+ }
+
+ @PostMapping("/books")
+ public ResponseEntity addBook(@RequestBody NewBook request) {
+ Book book = catalogue.addBook(request.title(), request.format(), request.shelf());
+ return ResponseEntity.created(URI.create("/api/books/" + book.getId())).body(BookView.of(book));
+ }
+
+ @PutMapping("/books/{id}/rating")
+ public BookView rate(@PathVariable long id, @RequestBody NewRating request) {
+ return BookView.of(catalogue.rate(id, request.rating()));
+ }
+
+ @GetMapping("/books/top-rated")
+ public List topRated() {
+ return catalogue.topRated().stream().map(BookView::of).toList();
+ }
+
+ @GetMapping("/shelves/{shelf}")
+ public List shelf(@PathVariable String shelf) {
+ return catalogue.shelf(shelf).stream().map(BookView::of).toList();
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java
new file mode 100644
index 0000000..aa0e899
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java
@@ -0,0 +1,41 @@
+package com.amigoscode.realdb.catalogue;
+
+import java.math.BigDecimal;
+import java.util.List;
+import org.springframework.data.domain.Limit;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+public class CatalogueService {
+
+ static final int TOP_RATED_SIZE = 3;
+
+ private final BookRepository books;
+
+ public CatalogueService(BookRepository books) {
+ this.books = books;
+ }
+
+ @Transactional
+ public Book addBook(String title, Format format, String shelf) {
+ return books.save(new Book(title, format, shelf));
+ }
+
+ @Transactional
+ public Book rate(long bookId, BigDecimal rating) {
+ Book book = books.findById(bookId).orElseThrow(() -> new BookNotFoundException(bookId));
+ book.rate(rating);
+ return book;
+ }
+
+ @Transactional(readOnly = true)
+ public List topRated() {
+ return books.findTopRated(Limit.of(TOP_RATED_SIZE));
+ }
+
+ @Transactional(readOnly = true)
+ public List shelf(String shelf) {
+ return books.findByShelf(shelf);
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Format.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Format.java
new file mode 100644
index 0000000..df65f14
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Format.java
@@ -0,0 +1,8 @@
+package com.amigoscode.realdb.catalogue;
+
+public enum Format {
+ PAPERBACK,
+ HARDCOVER,
+ EBOOK,
+ AUDIOBOOK
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java
new file mode 100644
index 0000000..5d8a0a7
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java
@@ -0,0 +1,8 @@
+package com.amigoscode.realdb.subscription;
+
+public class InvalidEmailException extends RuntimeException {
+
+ public InvalidEmailException(String email) {
+ super("Not an email address: " + email);
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java
new file mode 100644
index 0000000..5f73e69
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java
@@ -0,0 +1,39 @@
+package com.amigoscode.realdb.subscription;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import java.time.Instant;
+
+@Entity
+@Table(name = "subscriber")
+public class Subscriber {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @Column(nullable = false)
+ private String email;
+
+ @Column(name = "subscribed_at", nullable = false, insertable = false, updatable = false)
+ private Instant subscribedAt;
+
+ protected Subscriber() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public Instant getSubscribedAt() {
+ return subscribedAt;
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java
new file mode 100644
index 0000000..e610bac
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java
@@ -0,0 +1,27 @@
+package com.amigoscode.realdb.subscription;
+
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.Repository;
+import org.springframework.data.repository.query.Param;
+import org.springframework.transaction.annotation.Transactional;
+
+/** The acceptance checks call subscribe by name: fix it, do not rename it. */
+public interface SubscriberRepository extends Repository {
+
+ /**
+ * Adds the address unless it is already subscribed, in any capitalisation. One statement, so two
+ * requests for the same address at the same moment cannot both insert it.
+ *
+ * @return 1 if the address was added, 0 if it was already there
+ */
+ @Modifying
+ @Transactional
+ @Query(value = """
+ insert into subscriber (email) values (:email)
+ on conflict (lower(email)) do nothing
+ """, nativeQuery = true)
+ int subscribe(@Param("email") String email);
+
+ long count();
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java
new file mode 100644
index 0000000..fe55578
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java
@@ -0,0 +1,29 @@
+package com.amigoscode.realdb.subscription;
+
+import java.util.Map;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class SubscriptionController {
+
+ public record NewSubscriber(String email) {
+ }
+
+ private final SubscriptionService subscriptions;
+
+ public SubscriptionController(SubscriptionService subscriptions) {
+ this.subscriptions = subscriptions;
+ }
+
+ /** 201 for a new subscriber, 200 if the address was already subscribed. */
+ @PostMapping("/api/subscribers")
+ public ResponseEntity> subscribe(@RequestBody NewSubscriber request) {
+ SubscriptionService.Outcome outcome = subscriptions.subscribe(request.email());
+ HttpStatus status = outcome == SubscriptionService.Outcome.SUBSCRIBED ? HttpStatus.CREATED : HttpStatus.OK;
+ return ResponseEntity.status(status).body(Map.of("outcome", outcome.name()));
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java
new file mode 100644
index 0000000..44c176d
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java
@@ -0,0 +1,27 @@
+package com.amigoscode.realdb.subscription;
+
+import java.util.regex.Pattern;
+import org.springframework.stereotype.Service;
+
+@Service
+public class SubscriptionService {
+
+ public enum Outcome { SUBSCRIBED, ALREADY_SUBSCRIBED }
+
+ private static final Pattern EMAIL = Pattern.compile("[^@\\s]+@[^@\\s]+\\.[^@\\s]+");
+
+ private final SubscriberRepository subscribers;
+
+ public SubscriptionService(SubscriberRepository subscribers) {
+ this.subscribers = subscribers;
+ }
+
+ /** Subscribes an address to the newsletter. Subscribing twice is fine: the second time changes nothing. */
+ public Outcome subscribe(String email) {
+ String address = email == null ? "" : email.strip();
+ if (!EMAIL.matcher(address).matches()) {
+ throw new InvalidEmailException(email);
+ }
+ return subscribers.subscribe(address) == 1 ? Outcome.SUBSCRIBED : Outcome.ALREADY_SUBSCRIBED;
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/application.properties b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/application.properties
new file mode 100644
index 0000000..7ba0fda
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/application.properties
@@ -0,0 +1,13 @@
+spring.application.name=testing-with-a-real-database
+
+# Postgres from compose.yaml. Port 5456 so it does not clash with a Postgres you already run.
+spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5456/shop}
+spring.datasource.username=${DB_USER:shop}
+spring.datasource.password=${DB_PASSWORD:shop}
+
+# The schema comes from Flyway (src/main/resources/db/migration), never from Hibernate.
+spring.jpa.hibernate.ddl-auto=none
+spring.jpa.open-in-view=false
+
+# Uncomment to see every SQL statement.
+# logging.level.org.hibernate.SQL=DEBUG
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V1__create_catalogue.sql b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V1__create_catalogue.sql
new file mode 100644
index 0000000..d2d099d
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V1__create_catalogue.sql
@@ -0,0 +1,20 @@
+create table book (
+ id bigint generated by default as identity primary key,
+ title text not null,
+ format varchar(20) not null,
+ rating numeric(2, 1), -- null until the book has its first review
+ shelf text not null,
+ added_at timestamptz not null default now(),
+ constraint book_format_check check (format in ('PAPERBACK', 'HARDCOVER', 'EBOOK')),
+ constraint book_rating_check check (rating between 1.0 and 5.0)
+);
+
+create table subscriber (
+ id bigint generated by default as identity primary key,
+ email text not null,
+ subscribed_at timestamptz not null default now()
+);
+
+-- One subscription per address, whatever the capitalisation:
+-- Ann@Example.com and ann@example.com are the same person.
+create unique index subscriber_email_key on subscriber (lower(email));
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V2__allow_audiobooks.sql b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V2__allow_audiobooks.sql
new file mode 100644
index 0000000..1e6c95a
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V2__allow_audiobooks.sql
@@ -0,0 +1,4 @@
+-- Format.AUDIOBOOK was added to the Java enum. The database has to accept it too.
+alter table book drop constraint book_format_check;
+alter table book add constraint book_format_check
+ check (format in ('PAPERBACK', 'HARDCOVER', 'EBOOK', 'AUDIOBOOK'));
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java
new file mode 100644
index 0000000..473f9ba
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java
@@ -0,0 +1,44 @@
+package com.amigoscode.realdb.catalogue;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.realdb.support.PostgresTest;
+import java.math.BigDecimal;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.data.domain.Limit;
+
+/** The repository against real Postgres, with the schema from the Flyway migrations. */
+@DataJpaTest
+class BookRepositoryTest extends PostgresTest {
+
+ @Autowired
+ BookRepository books;
+
+ @Test
+ void topRatedComesBestFirstAndUnratedBooksLast() {
+ rated("Dune", "4.8");
+ rated("Emma", "3.9");
+ books.save(new Book("No Reviews Yet", Format.PAPERBACK, "fiction"));
+ rated("Hamlet", "4.2");
+
+ assertThat(books.findTopRated(Limit.of(3)))
+ .extracting(Book::getTitle)
+ .containsExactly("Dune", "Hamlet", "Emma");
+ }
+
+ @Test
+ void savesAnAudiobook() {
+ Book saved = books.saveAndFlush(new Book("Dune", Format.AUDIOBOOK, "fiction"));
+
+ assertThat(books.findById(saved.getId())).get()
+ .extracting(Book::getFormat)
+ .isEqualTo(Format.AUDIOBOOK);
+ }
+
+ private void rated(String title, String rating) {
+ Book book = books.save(new Book(title, Format.PAPERBACK, "fiction"));
+ book.rate(new BigDecimal(rating));
+ }
+}
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java
new file mode 100644
index 0000000..52384a8
--- /dev/null
+++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java
@@ -0,0 +1,66 @@
+package com.amigoscode.realdb.catalogue;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.realdb.catalogue.CatalogueController.BookView;
+import com.amigoscode.realdb.catalogue.CatalogueController.NewBook;
+import com.amigoscode.realdb.support.PostgresTest;
+import java.util.List;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.server.LocalServerPort;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.RestClient;
+
+/**
+ * The whole application over HTTP, against the same Postgres as the other tests.
+ *
+ * Not @Transactional: the server handles each request on its own thread, in its own transaction,
+ * and commits it. A transaction around the test would roll back nothing the server did, and the
+ * server could not see anything the test wrote in it. PostgresTest empties the tables before each test.
+ */
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class CatalogueApiTest extends PostgresTest {
+
+ @LocalServerPort
+ int port;
+
+ RestClient http;
+
+ @BeforeEach
+ void client() {
+ http = RestClient.create("http://localhost:" + port);
+ }
+
+ @Test
+ void addsABook() {
+ ResponseEntity