data-jpa-3-to-4: Spring Data JPA 3.5 vs 4.2 side by side - package moves, nullness, Specification, keyset, Page JSON, Jackson 3, test slices, real transcripts

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7N4ZDbUtA3ofqAqRV
This commit is contained in:
Ankur Mhatre
2026-12-03 09:31:28 +05:30
co-authored by Claude Sonnet 5.5
parent 3f061c5e5d
commit 7a2bcc1eb6
100 changed files with 2314 additions and 0 deletions
+60
View File
@@ -0,0 +1,60 @@
# data-jpa-3-to-4
Companion code for **Spring Data JPA 3 to 4 Migration Guide (Spring Boot 3 to 4): What Breaks and How to Fix It** on
[ankurm.com](https://ankurm.com/spring-data-jpa-3-to-4-migration-guide/).
One source tree, built twice. `common/` holds the application and tests that compile unchanged on both generations;
`boot3/` and `boot4/` hold a `pom.xml` each plus the few tests whose code has to differ. The same test writes
`output/NN-name-boot3.txt` and `output/NN-name-boot4.txt`, so a before/after is a diff of two files.
## Versions
| Component | boot3 | boot4 |
|---|---|---|
| Spring Boot | 3.5.16 | 4.2.0 |
| Spring Framework | 6.2.19 | 7.1.0 |
| Spring Data JPA | 3.5.13 | 4.2.0 |
| Hibernate ORM | 6.6.53.Final | 7.4.15.Final |
| Jakarta Persistence | 3.1.0 | 3.2.0 |
| Jackson databind | 2.21.4 | 3.1.8 |
| Querydsl (`com.querydsl`) | 5.1.0 | 5.1.0 |
| H2 | 2.3.232 | 2.5.252 |
| JDK | 25 (Temurin 25.0.5) | 25 |
The boot4 tests were also run on Spring Boot 4.0.10 and 4.1.3. Output 15 and 16 were added afterwards and are
recorded for 3.5.16 and 4.2.0 only.
## Run it
```bash
(cd boot3 && mvn test)
(cd boot4 && mvn test)
./scripts/run-all.sh # regenerates every file in output/
PG_URL=jdbc:postgresql://localhost:5432/postgres PG_USER=postgres PG_PASSWORD=... ./scripts/run-all.sh # also output 16
```
Output 16 needs a real PostgreSQL (captured on 16.15). The tests recreate their tables, so point it at a scratch database.
## What is where
| Output | Topic |
|---|---|
| `01-package-moves` | types that moved or vanished, read from the jars; test slice and Boot package moves |
| `02-derived-queries` | Criteria vs JPQL, `NULLS LAST`, non-unique results |
| `03-single-result` | `getSingleResult()` and `getSingleResultOrNull()` |
| `04-hibernate`, `25-native-temporal-compat` | native query temporal types, `save()` with a hand-assigned id |
| `05-specifications-querydsl`, `23-bulk-specification` | Specification null handling, bulk delete and update, Querydsl |
| `06`, `15`, `16` keyset | keyset scrolling, including nullable sort columns on H2 and PostgreSQL |
| `07-nullness` | `@NonNullApi` vs JSpecify `@NullMarked` |
| `08-wiring-and-records` | `EntityManager` beans, a record annotated `@Entity` |
| `09`, `11` page JSON | `PageImpl`, `PagedModel`, `Slice`, `Window` |
| `10`, `14` Jackson | primitives in request bodies, `spring.jackson.use-jackson2-defaults` |
| `12`, `13` projections | DTO projections and when a broken one fails |
| `17`, `18` repository API | public method diff, produced by `scripts/ApiDump.java` |
| `19-compile-errors` | `broken/boot3-style/*.java` compiled against both classpaths |
| `20-metamodel-processor` | `hibernate-jpamodelgen` vs `hibernate-processor` |
| `21-querydsl` | record embeddable crash in `com.querydsl` 5.1.0; the OpenFeign fork |
| `22-native-parser-property` | where `spring.data.jpa.query.native.parser` lived |
| `24-renamed-property` | `spring.dao.exceptiontranslation.enabled` |
Boot 3.5 reached the end of open-source support in June 2026; it is here as the "before" side of the comparison.
+109
View File
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.16</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>data-jpa-3-to-4-boot3</artifactId>
<version>1.0.0</version>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
<classifier>jakarta</classifier>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource><directory>../common/src/main/resources</directory></resource>
</resources>
<plugins>
<!-- The tests and the code under test that is identical on both generations live in ../common -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>common-main</id>
<phase>generate-sources</phase>
<goals><goal>add-source</goal></goals>
<configuration><sources><source>../common/src/main/java</source></sources></configuration>
</execution>
<execution>
<id>common-test</id>
<phase>generate-test-sources</phase>
<goals><goal>add-test-source</goal></goals>
<configuration><sources><source>../common/src/test/java</source></sources></configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
</path>
<path>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<classifier>jakarta</classifier>
</path>
<path>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>${jakarta-persistence.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,27 @@
package com.ankurm.jpamig;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.repo.BookRepository;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
/** Boot 3.5 imports. Compare with boot4/src/test/java: only the import lines differ. */
@DataJpaTest
@AutoConfigureTestDatabase
class BookSliceTest {
@Autowired TestEntityManager em;
@Autowired BookRepository books;
@Test
void findsByIsbn() {
em.persistAndFlush(new Book("Dune", null, "978-0002", "9.99", LocalDate.of(1965, 8, 1)));
assertEquals("Dune", books.findByIsbn("978-0002").orElseThrow().getTitle());
}
}
@@ -0,0 +1,27 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.domain.Book_;
import com.ankurm.jpamig.repo.BookRepository;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.domain.Specification;
/** Spring Data JPA 3.5: bulk delete takes the same Specification you query with. */
@SpringBootTest
class BulkSpecificationTest {
@Autowired BookRepository books;
@Test
void bulkDelete() {
Seed.books(books);
var t = new Transcript("23-bulk-specification");
Specification<Book> old = (root, query, cb) -> cb.lessThan(root.get(Book_.publishedOn), LocalDate.of(1900, 1, 1));
t.attempt("books.delete(specification)", () -> books.delete(old));
t.sql();
t.write();
}
}
+109
View File
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>data-jpa-3-to-4-boot4</artifactId>
<version>1.0.0</version>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
<classifier>jakarta</classifier>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource><directory>../common/src/main/resources</directory></resource>
</resources>
<plugins>
<!-- The tests and the code under test that is identical on both generations live in ../common -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>common-main</id>
<phase>generate-sources</phase>
<goals><goal>add-source</goal></goals>
<configuration><sources><source>../common/src/main/java</source></sources></configuration>
</execution>
<execution>
<id>common-test</id>
<phase>generate-test-sources</phase>
<goals><goal>add-test-source</goal></goals>
<configuration><sources><source>../common/src/test/java</source></sources></configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-processor</artifactId>
<version>${hibernate.version}</version>
</path>
<path>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<classifier>jakarta</classifier>
</path>
<path>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>${jakarta-persistence.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,27 @@
package com.ankurm.jpamig;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.repo.BookRepository;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.jpa.test.autoconfigure.TestEntityManager;
/** Boot 4 imports. Compare with boot3/src/test/java: only the import lines differ. */
@DataJpaTest
@AutoConfigureTestDatabase
class BookSliceTest {
@Autowired TestEntityManager em;
@Autowired BookRepository books;
@Test
void findsByIsbn() {
em.persistAndFlush(new Book("Dune", null, "978-0002", "9.99", LocalDate.of(1965, 8, 1)));
assertEquals("Dune", books.findByIsbn("978-0002").orElseThrow().getTitle());
}
}
@@ -0,0 +1,38 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.domain.Book_;
import com.ankurm.jpamig.repo.BookRepository;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.domain.PredicateSpecification;
import org.springframework.data.jpa.domain.UpdateSpecification;
import org.springframework.transaction.support.TransactionTemplate;
/** Spring Data JPA 4: one PredicateSpecification serves reads, bulk deletes and bulk updates. */
@SpringBootTest
class BulkSpecificationTest {
@Autowired BookRepository books;
@Autowired TransactionTemplate tx;
@Test
void bulkOperations() {
Seed.books(books);
var t = new Transcript("23-bulk-specification");
PredicateSpecification<Book> old = (from, cb) -> cb.lessThan(from.get(Book_.publishedOn), LocalDate.of(1900, 1, 1));
PredicateSpecification<Book> dune = (from, cb) -> cb.equal(from.get(Book_.title), "Dune");
t.attempt("books.count(predicate)", () -> books.count(old));
t.sql();
UpdateSpecification<Book> retitle = UpdateSpecification
.<Book>update((root, update, cb) -> update.set(root.get(Book_.title), "Dune (1965)"))
.where(dune);
t.attempt("books.update(UpdateSpecification)", () -> tx.execute(s -> books.update(retitle)));
t.sql();
t.attempt("books.delete(predicate)", () -> books.delete(old));
t.sql();
t.write();
}
}
@@ -0,0 +1,9 @@
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.repo.BookRepository;
import org.springframework.data.jpa.domain.Specification;
class DeleteBySpecification {
long purge(BookRepository books, Specification<Book> old) {
return books.delete(old);
}
}
@@ -0,0 +1,15 @@
import com.ankurm.jpamig.domain.Book;
import org.hibernate.Session;
import org.hibernate.annotations.Where;
class HibernateSessionApi {
@Where(clause = "deleted = false")
java.util.List<Book> filtered;
void write(Session session, Book book) {
session.save(book);
session.saveOrUpdate(book);
session.update(book);
session.delete(book);
}
}
@@ -0,0 +1,7 @@
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
class JacksonCustomizer {
Jackson2ObjectMapperBuilderCustomizer dates() {
return builder -> builder.simpleDateFormat("dd.MM.yyyy");
}
}
@@ -0,0 +1,9 @@
import org.springframework.data.mapping.PropertyPath;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.data.util.TypeInformation;
class PackageMoves {
TypeInformation<?> t = TypeInformation.of(String.class);
PropertyPath p;
PropertyReferenceException e;
}
@@ -0,0 +1,7 @@
import org.springframework.data.querydsl.QPageRequest;
class QueryDslPaging {
Object first() {
return new QPageRequest(0, 20);
}
}
@@ -0,0 +1,7 @@
import org.springframework.data.annotation.PersistenceConstructor;
class RemovedAnnotations {
@PersistenceConstructor
RemovedAnnotations() {
}
}
@@ -0,0 +1,11 @@
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.repo.BookRepository;
/** Deprecated long ago, still present in Spring Data JPA 4.2: warnings, not errors. */
class StillCompiles {
void old(BookRepository books) {
Book a = books.getOne(1L);
Book b = books.getById(1L);
books.deleteInBatch(java.util.List.of(a, b));
}
}
@@ -0,0 +1,8 @@
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
class TestSliceImports {
}
@@ -0,0 +1,8 @@
import com.ankurm.jpamig.domain.Book;
import org.springframework.data.jpa.domain.Specification;
class WhereNull {
Specification<Book> start() {
return Specification.where(null);
}
}
@@ -0,0 +1,14 @@
import jakarta.persistence.Embeddable;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
class Invoice {
@Id Long id;
@Embedded Amount total;
}
@Embeddable
record Amount(java.math.BigDecimal value, String currency) {
}
@@ -0,0 +1,12 @@
package com.ankurm.jpamig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** The same application source is compiled twice: once by boot3/pom.xml and once by boot4/pom.xml. */
@SpringBootApplication
public class JpaMigrationApplication {
public static void main(String[] args) {
SpringApplication.run(JpaMigrationApplication.class, args);
}
}
@@ -0,0 +1,22 @@
package com.ankurm.jpamig;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.resource.jdbc.spi.StatementInspector;
/** Records every SQL statement Hibernate sends, so tests can print them. */
public class SqlCapture implements StatementInspector {
private static final List<String> SQL = new ArrayList<>();
@Override
public synchronized String inspect(String sql) {
SQL.add(sql);
return sql;
}
public static synchronized List<String> drain() {
List<String> copy = List.copyOf(SQL);
SQL.clear();
return copy;
}
}
@@ -0,0 +1,52 @@
package com.ankurm.jpamig.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.math.BigDecimal;
import java.time.LocalDate;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
private String subtitle;
@Column(nullable = false)
private String isbn;
@Embedded
private Money price;
private LocalDate publishedOn;
protected Book() {
}
public Book(String title, String subtitle, String isbn, String amount, LocalDate publishedOn) {
this.title = title;
this.subtitle = subtitle;
this.isbn = isbn;
this.price = new Money(new BigDecimal(amount), "EUR");
this.publishedOn = publishedOn;
}
public Long getId() { return id; }
/** Only used to show what happens when an application assigns a generated id by hand. */
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getSubtitle() { return subtitle; }
public String getIsbn() { return isbn; }
public Money getPrice() { return price; }
public LocalDate getPublishedOn() { return publishedOn; }
}
@@ -0,0 +1,25 @@
package com.ankurm.jpamig.domain;
import jakarta.persistence.Embeddable;
import java.math.BigDecimal;
/**
* Deliberately a class, not a record: querydsl-apt 5.1.0 (the version both Boot 3.5 and Boot 4.2 manage)
* crashes the compiler on a record embeddable. See broken/querydsl-record and scripts/run-all.sh.
*/
@Embeddable
public class Money {
private BigDecimal amount;
private String currency;
protected Money() {
}
public Money(BigDecimal amount, String currency) {
this.amount = amount;
this.currency = currency;
}
public BigDecimal getAmount() { return amount; }
public String getCurrency() { return currency; }
}
@@ -0,0 +1,13 @@
package com.ankurm.jpamig.jsnull;
import com.ankurm.jpamig.domain.Book;
import org.jspecify.annotations.Nullable;
import org.springframework.data.repository.Repository;
public interface JSpecifyRepository extends Repository<Book, Long> {
Book findByIsbn(String isbn);
@Nullable Book findFirstByTitle(String title);
java.util.List<Book> findBySubtitle(@Nullable String subtitle);
}
@@ -0,0 +1,3 @@
/** The JSpecify way. */
@org.jspecify.annotations.NullMarked
package com.ankurm.jpamig.jsnull;
@@ -0,0 +1,8 @@
package com.ankurm.jpamig.legacynull;
import com.ankurm.jpamig.domain.Book;
import org.springframework.data.repository.Repository;
public interface LegacyNullRepository extends Repository<Book, Long> {
Book findByIsbn(String isbn);
}
@@ -0,0 +1,3 @@
/** The Spring Data 3.x way of declaring a null-restricted package. */
@org.springframework.lang.NonNullApi
package com.ankurm.jpamig.legacynull;
@@ -0,0 +1,7 @@
package com.ankurm.jpamig.repo;
import java.math.BigDecimal;
/** A DTO whose second component is NOT a top-level property of Book (it lives in price.amount). */
public record BookAmount(String title, BigDecimal amount) {
}
@@ -0,0 +1,49 @@
package com.ankurm.jpamig.repo;
import com.ankurm.jpamig.domain.Book;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Window;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
/** Compiles unchanged on Spring Data JPA 3.5 and 4.2. */
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book>,
QuerydslPredicateExecutor<Book> {
Optional<Book> findByIsbn(String isbn);
List<Book> findByPriceAmountGreaterThan(BigDecimal min, Sort sort);
Optional<Book> findByTitleStartingWith(String prefix);
@Query("select b.title || ' (' || left(b.isbn, 3) || ')' from Book b where b.isbn = :isbn")
String titleWithIsbnPrefix(String isbn);
List<BookTitle> findTitlesByIsbnStartingWith(String prefix);
@Query("select new com.ankurm.jpamig.repo.BookAmount(b.title, b.price.amount) from Book b where b.isbn = :isbn")
BookAmount amountByIsbn(String isbn);
Page<Book> findPageBy(Pageable pageable);
Slice<Book> findSliceBy(Pageable pageable);
Window<Book> findFirst2ByOrderByTitleAscIdAsc(ScrollPosition position);
Window<Book> findFirst2ByOrderBySubtitleAscIdAsc(ScrollPosition position);
Window<Book> findFirst2By(Sort sort, ScrollPosition position);
@Query(value = "select published_on, current_timestamp, cast('10:15:00' as time) from book where isbn = :isbn",
nativeQuery = true)
List<Object[]> nativeTemporals(String isbn);
}
@@ -0,0 +1,24 @@
package com.ankurm.jpamig.repo;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.domain.Book_;
import java.time.LocalDate;
import org.springframework.data.jpa.domain.Specification;
/** Book_ is generated by hibernate-jpamodelgen on Boot 3 and by hibernate-processor on Boot 4. */
public final class BookSpecifications {
private BookSpecifications() {
}
public static Specification<Book> publishedBefore(LocalDate date) {
return (root, query, cb) -> cb.lessThan(root.get(Book_.publishedOn), date);
}
public static Specification<Book> titleContains(String fragment) {
// unrestricted() exists on both generations; use it instead of where(null)
return fragment == null
? Specification.unrestricted()
: (root, query, cb) -> cb.like(root.get(Book_.title), "%" + fragment + "%");
}
}
@@ -0,0 +1,5 @@
package com.ankurm.jpamig.repo;
/** A DTO whose components match Book's properties by name. */
public record BookTitle(String title, String isbn) {
}
@@ -0,0 +1,55 @@
package com.ankurm.jpamig.web;
import com.ankurm.jpamig.repo.BookRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Window;
import org.springframework.data.web.PagedModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookController {
private final BookRepository books;
public BookController(BookRepository books) {
this.books = books;
}
private static PageRequest firstTwo() {
return PageRequest.of(0, 2, Sort.by("title"));
}
/** Returns the PageImpl itself: its JSON shape is not a contract. */
@GetMapping("/page")
public Page<BookView> page() {
return books.findPageBy(firstTwo()).map(BookView::of);
}
/** The stable shape, spelled out in code so it does not depend on configuration. */
@GetMapping("/paged-model")
public PagedModel<BookView> pagedModel() {
return new PagedModel<>(books.findPageBy(firstTwo()).map(BookView::of));
}
@GetMapping("/slice")
public Slice<BookView> slice() {
return books.findSliceBy(firstTwo()).map(BookView::of);
}
@GetMapping("/window")
public Window<BookView> window() {
return books.findFirst2ByOrderByTitleAscIdAsc(ScrollPosition.keyset()).map(BookView::of);
}
@PostMapping("/books")
public NewBook echo(@RequestBody NewBook book) {
return book;
}
}
@@ -0,0 +1,10 @@
package com.ankurm.jpamig.web;
import com.ankurm.jpamig.domain.Book;
import java.time.LocalDate;
public record BookView(Long id, String title, String isbn, LocalDate publishedOn) {
static BookView of(Book b) {
return new BookView(b.getId(), b.getTitle(), b.getIsbn(), b.getPublishedOn());
}
}
@@ -0,0 +1,5 @@
package com.ankurm.jpamig.web;
/** The primitive components matter: see the Jackson 3 section of the post. */
public record NewBook(String title, int copies, boolean signed) {
}
@@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:jpamig;DB_CLOSE_DELAY=-1
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.session_factory.statement_inspector=com.ankurm.jpamig.SqlCapture
logging.level.root=warn
spring.main.banner-mode=off
@@ -0,0 +1,27 @@
package com.ankurm.jpamig;
import com.ankurm.probe.ItemRepository;
import com.ankurm.probe.ProbeApplication;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
/** Same broken derived DTO projection on both generations: when does it fail? */
class BadProjectionStartupTest {
@Test
void whenDoesItFail() {
var t = new Transcript("13-bad-projection");
try (var ctx = new SpringApplicationBuilder(ProbeApplication.class).web(WebApplicationType.NONE)
.run("--spring.datasource.url=jdbc:h2:mem:probe")) {
t.line("application startup -> succeeded");
t.attempt("first call of findByTitle(\"x\")", () -> ctx.getBean(ItemRepository.class).findByTitle("x"));
} catch (Exception e) {
Throwable root = e;
while (root.getCause() != null) root = root.getCause();
t.line("application startup -> FAILED");
t.line(" root cause " + root.getClass().getName() + ": " + root.getMessage());
}
t.write();
}
}
@@ -0,0 +1,31 @@
package com.ankurm.jpamig;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springframework.core.env.Environment;
/** Plain JDK HTTP client: no test-slice imports, so these tests are identical on both generations. */
final class Http {
private static final HttpClient CLIENT = HttpClient.newHttpClient();
static void get(Environment env, Transcript t, String path) throws Exception {
send(t, "GET " + path, request(env, path).GET().build());
}
static void post(Environment env, Transcript t, String path, String body) throws Exception {
send(t, "POST " + path + " " + body, request(env, path).header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body)).build());
}
private static HttpRequest.Builder request(Environment env, String path) {
return HttpRequest.newBuilder(URI.create("http://localhost:" + env.getProperty("local.server.port") + path));
}
private static void send(Transcript t, String label, HttpRequest r) throws Exception {
var res = CLIENT.send(r, HttpResponse.BodyHandlers.ofString());
t.line(label);
t.line(" " + res.statusCode() + " " + res.body().replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"...\""));
}
}
@@ -0,0 +1,27 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.repo.BookRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
/** spring.jackson.use-jackson2-defaults exists only on Boot 4; Boot 3.5 ignores it. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"spring.jackson.use-jackson2-defaults=true",
"spring.datasource.url=jdbc:h2:mem:j2;DB_CLOSE_DELAY=-1"})
class Jackson2DefaultsTest {
@Autowired BookRepository books;
@Autowired Environment env;
@Test
void restoredDefaults() throws Exception {
Seed.books(books);
var t = new Transcript("14-jackson2-defaults");
t.line("spring.jackson.use-jackson2-defaults=true");
Http.get(env, t, "/page");
Http.post(env, t, "/books", "{\"title\":\"Dune\"}");
t.write();
}
}
@@ -0,0 +1,39 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.repo.BookRepository;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Window;
/** Same keyset scroll over a nullable column, but with NULLs sorting last on ASC, as PostgreSQL does. */
@SpringBootTest(properties = "spring.datasource.url=jdbc:h2:mem:high;DB_CLOSE_DELAY=-1;DEFAULT_NULL_ORDERING=HIGH")
class KeysetNullsHighTest {
@Autowired BookRepository books;
@Test
void nullsSortLast() {
Seed.books(books);
var t = new Transcript("15-keyset-nulls-high");
var found = new ArrayList<String>();
ScrollPosition p = ScrollPosition.keyset();
try {
for (int page = 1; page <= 6; page++) {
Window<Book> w = books.findFirst2ByOrderBySubtitleAscIdAsc(p);
w.forEach(b -> found.add(b.getTitle() + "/" + b.getSubtitle()));
t.line("window " + page + ": " + w.map(Book::getTitle).getContent() + " hasNext=" + w.hasNext());
t.sql();
if (!w.hasNext()) break;
p = w.positionAt(w.size() - 1);
}
} catch (Exception e) {
t.line("throws " + e.getClass().getName() + ": " + String.valueOf(e.getMessage()).lines().findFirst().orElse(""));
}
t.line("rows seen: " + found.size() + " of " + books.count() + " " + found);
t.write();
}
}
@@ -0,0 +1,65 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.repo.BookRepository;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Window;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
/** Runs only with -Dpg.url=jdbc:postgresql://... (see scripts/run-all.sh). */
@EnabledIfSystemProperty(named = "pg.url", matches = ".+")
@SpringBootTest
class KeysetPostgresTest {
@DynamicPropertySource
static void postgres(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", () -> System.getProperty("pg.url"));
r.add("spring.datasource.username", () -> System.getProperty("pg.user", "postgres"));
r.add("spring.datasource.password", () -> System.getProperty("pg.password", ""));
}
@Autowired BookRepository books;
@Test
void nullableSortColumnOnPostgres() {
Seed.books(books);
var t = new Transcript("16-keyset-postgresql");
var found = new ArrayList<String>();
ScrollPosition p = ScrollPosition.keyset();
for (int page = 1; page <= 6; page++) {
Window<Book> w = books.findFirst2ByOrderBySubtitleAscIdAsc(p);
w.forEach(b -> found.add(b.getTitle() + "/" + b.getSubtitle()));
t.line("window " + page + ": " + w.map(Book::getTitle).getContent() + " hasNext=" + w.hasNext());
if (!w.hasNext()) break;
p = w.positionAt(w.size() - 1);
}
t.line("rows seen: " + found.size() + " of " + books.count() + " " + found);
for (var order : java.util.List.of(Sort.Order.asc("subtitle").nullsFirst(),
Sort.Order.asc("subtitle").nullsLast())) {
t.line("-- same scroll with an explicit Sort: subtitle ASC " + order.getNullHandling() + ", id");
var sort = Sort.by(order, Sort.Order.asc("id"));
t.attempt("rows seen", () -> scrollAll(sort));
}
t.write();
}
private String scrollAll(Sort sort) {
var all = new ArrayList<String>();
ScrollPosition q = ScrollPosition.keyset();
for (int page = 1; page <= 6; page++) {
Window<Book> w = books.findFirst2By(sort, q);
w.forEach(b -> all.add(b.getTitle() + "/" + b.getSubtitle()));
if (!w.hasNext()) break;
q = w.positionAt(w.size() - 1);
}
return all.size() + " of " + books.count() + " " + all;
}
}
@@ -0,0 +1,25 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.repo.BookRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/** Hibernate 7's switch back to java.sql types for native queries. Hibernate 6.6 already returns them. */
@SpringBootTest(properties = {"spring.jpa.properties.hibernate.query.native.prefer_jdbc_datetime_types=true",
"spring.datasource.url=jdbc:h2:mem:temporal;DB_CLOSE_DELAY=-1"})
class NativeTemporalCompatTest {
@Autowired BookRepository books;
@Test
void jdbcTypesAgain() {
Seed.books(books);
var t = new Transcript("25-native-temporal-compat");
t.line("hibernate.query.native.prefer_jdbc_datetime_types=true");
for (Object o : books.nativeTemporals("978-0002").get(0)) {
t.line("native query column -> " + o.getClass().getName());
}
t.write();
}
}
@@ -0,0 +1,33 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.jsnull.JSpecifyRepository;
import com.ankurm.jpamig.legacynull.LegacyNullRepository;
import com.ankurm.jpamig.repo.BookRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NullnessTest {
@Autowired BookRepository books;
@Autowired LegacyNullRepository legacy;
@Autowired JSpecifyRepository jspecify;
@Test
void whoEnforcesWhat() {
Seed.books(books);
var t = new Transcript("07-nullness");
t.line("-- package marked @org.springframework.lang.NonNullApi");
t.attempt("Book findByIsbn(missing)", () -> legacy.findByIsbn("nope"));
t.attempt("Book findByIsbn(null)", () -> legacy.findByIsbn(null));
t.line("-- package marked @org.jspecify.annotations.NullMarked");
t.attempt("Book findByIsbn(missing)", () -> jspecify.findByIsbn("nope"));
t.attempt("Book findByIsbn(null)", () -> jspecify.findByIsbn(null));
t.attempt("@Nullable Book findFirstByTitle(missing)", () -> jspecify.findFirstByTitle("nope"));
SqlCapture.drain();
t.attempt("findBySubtitle(@Nullable null).size", () -> jspecify.findBySubtitle(null).size());
t.sql();
t.write();
}
}
@@ -0,0 +1,37 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.repo.BookRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.core.env.Environment;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(OutputCaptureExtension.class)
class PageJsonTest {
@Autowired BookRepository books;
@Autowired Environment env;
@Test
void defaultShapes(CapturedOutput output) throws Exception {
Seed.books(books);
var t = new Transcript("09-page-json");
for (String path : new String[] {"/page", "/paged-model", "/slice", "/window"}) {
Http.get(env, t, path);
}
output.getAll().lines().filter(l -> l.contains("PageImpl"))
.map(l -> l.substring(Math.max(0, l.indexOf(" WARN ") + 1))).distinct()
.forEach(l -> t.line("log: " + l.replaceAll("\\s+\\d+ --- ", " --- ")));
t.write();
var j = new Transcript("10-jackson-request");
Http.post(env, j, "/books", "{\"title\":\"Dune\",\"copies\":3,\"signed\":true}");
Http.post(env, j, "/books", "{\"title\":\"Dune\"}");
Http.post(env, j, "/books", "{\"title\":\"Dune\",\"copies\":null,\"signed\":false}");
j.write();
}
}
@@ -0,0 +1,25 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.repo.BookRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"spring.data.web.pageable.serialization-mode=via-dto",
"spring.datasource.url=jdbc:h2:mem:viadto;DB_CLOSE_DELAY=-1"})
class PageViaDtoTest {
@Autowired BookRepository books;
@Autowired Environment env;
@Test
void viaDto() throws Exception {
Seed.books(books);
var t = new Transcript("11-page-json-via-dto");
t.line("spring.data.web.pageable.serialization-mode=via-dto");
Http.get(env, t, "/page");
t.write();
}
}
@@ -0,0 +1,156 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.domain.QBook;
import com.ankurm.jpamig.repo.BookRepository;
import com.ankurm.jpamig.repo.BookSpecifications;
import jakarta.persistence.EntityManagerFactory;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.KeysetScrollPosition;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Window;
import org.springframework.data.jpa.domain.Specification;
@SpringBootTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true")
class QueryBehaviourTest {
@Autowired BookRepository books;
@Autowired EntityManagerFactory emf;
@BeforeEach
void seed() {
Seed.books(books);
}
@Test
void derivedQueries() {
var t = new Transcript("02-derived-queries");
Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
stats.clear();
t.line("findByPriceAmountGreaterThan(8, title asc):");
books.findByPriceAmountGreaterThan(new BigDecimal("8"), Sort.by("title"))
.forEach(b -> t.line(" " + b.getTitle()));
t.sql();
t.line("Query strings Hibernate statistics recorded for that call:");
for (String q : stats.getQueries()) {
t.line(" " + q);
}
var nullsLast = Sort.by(Sort.Order.asc("subtitle").nullsLast(), Sort.Order.asc("id"));
t.attempt("the same derived query with subtitle asc NULLS LAST",
() -> books.findByPriceAmountGreaterThan(new BigDecimal("8"), nullsLast).stream()
.map(b -> b.getTitle() + "/" + b.getSubtitle()).toList());
t.sql();
t.attempt("findByIsbn(missing)", () -> books.findByIsbn("nope"));
t.attempt("findByTitleStartingWith(\"\") with 5 rows", () -> books.findByTitleStartingWith(""));
t.attempt("@Query using || and left()", () -> books.titleWithIsbnPrefix("978-0002"));
SqlCapture.drain();
t.write();
}
@Test
void dtoProjections() {
var t = new Transcript("12-dto-projections");
t.attempt("record BookTitle(title, isbn), derived", () -> books.findTitlesByIsbnStartingWith("978-0001"));
t.sql();
t.attempt("record BookAmount via @Query constructor expression", () -> books.amountByIsbn("978-0001"));
t.sql();
t.write();
}
@Test
void entityManagerSingleResult() {
var t = new Transcript("03-single-result");
try (var em = emf.createEntityManager()) {
t.attempt("em.createQuery(...).getSingleResult() on no rows",
() -> em.createQuery("select b from Book b where b.isbn = 'nope'", Book.class).getSingleResult());
t.attempt("jakarta.persistence.TypedQuery declares getSingleResultOrNull()",
() -> Arrays.stream(jakarta.persistence.TypedQuery.class.getMethods())
.anyMatch(m -> m.getName().equals("getSingleResultOrNull")));
}
t.write();
}
@Test
void hibernateUnderneath() {
var t = new Transcript("04-hibernate");
t.line("Hibernate " + org.hibernate.Version.getVersionString());
Object[] row = books.nativeTemporals("978-0002").get(0);
for (Object o : row) {
t.line("native query column -> " + o.getClass().getName());
}
t.attempt("read column 0 as java.sql.Date (old cast)", () -> (java.sql.Date) row[0]);
SqlCapture.drain();
var ghost = new Book("Ghost", null, "978-9999", "1.00", LocalDate.of(2000, 1, 1));
ghost.setId(4242L);
t.attempt("save() of a new entity with a hand-assigned @GeneratedValue id", () -> books.save(ghost).getId());
t.sql();
t.write();
}
@Test
void specificationsAndQuerydsl() {
var t = new Transcript("05-specifications-querydsl");
var old = BookSpecifications.publishedBefore(LocalDate.of(1900, 1, 1));
t.attempt("count(publishedBefore 1900)", () -> books.count(old));
t.attempt("count(titleContains(null) i.e. unrestricted)", () -> books.count(BookSpecifications.titleContains(null)));
t.attempt("spec.and((Specification) null)", () -> books.count(old.and((Specification<Book>) null)));
t.attempt("Specification.where((Specification) null)",
() -> books.count(Specification.where((Specification<Book>) null)));
t.attempt("findBy(spec, fluent).count",
() -> books.findBy(old, q -> q.sortBy(Sort.by("title")).all()).size());
var q = QBook.book;
t.attempt("Querydsl findAll(price > 10, title asc)",
() -> {
var out = new java.util.ArrayList<String>();
books.findAll(q.price.amount.gt(new BigDecimal("10")), q.title.asc())
.forEach(b -> out.add(b.getTitle()));
return out;
});
SqlCapture.drain();
t.write();
}
@Test
void keysetScrolling() {
var t = new Transcript("06-keyset-scrolling");
t.line("-- ORDER BY title, id (both columns NOT NULL)");
ScrollPosition pos = ScrollPosition.keyset();
for (int page = 1; page <= 3; page++) {
Window<Book> w = books.findFirst2ByOrderByTitleAscIdAsc(pos);
t.line("window " + page + ": " + w.map(Book::getTitle).getContent() + " hasNext=" + w.hasNext());
t.sql();
if (!w.hasNext()) break;
pos = w.positionAt(w.size() - 1);
t.line(" next position keys: " + new java.util.TreeMap<String, Object>(((KeysetScrollPosition) pos).getKeys()));
}
t.line("-- ORDER BY subtitle (nullable), id");
var found = new java.util.ArrayList<String>();
SqlCapture.drain();
try {
ScrollPosition p = ScrollPosition.keyset();
for (int page = 1; page <= 6; page++) {
Window<Book> w = books.findFirst2ByOrderBySubtitleAscIdAsc(p);
w.forEach(b -> found.add(b.getTitle() + "/" + b.getSubtitle()));
t.line("window " + page + ": " + w.map(Book::getTitle).getContent() + " hasNext=" + w.hasNext());
t.sql();
if (!w.hasNext()) break;
p = w.positionAt(w.size() - 1);
}
} catch (Exception e) {
t.line("throws " + e.getClass().getName() + ": " + String.valueOf(e.getMessage()).lines().findFirst().orElse(""));
}
t.line("rows seen: " + found.size() + " of " + books.count() + " " + found);
SqlCapture.drain();
t.write();
}
}
@@ -0,0 +1,24 @@
package com.ankurm.jpamig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
/** The Boot 3 property name, set on both generations. */
@SpringBootTest(properties = {"spring.dao.exceptiontranslation.enabled=false",
"spring.datasource.url=jdbc:h2:mem:prop;DB_CLOSE_DELAY=-1"})
class RenamedPropertyTest {
@Autowired ApplicationContext context;
@Test
void oldPropertyName() {
var t = new Transcript("24-renamed-property");
t.line("spring.dao.exceptiontranslation.enabled=false");
t.line("PersistenceExceptionTranslationPostProcessor beans: "
+ context.getBeanNamesForType(PersistenceExceptionTranslationPostProcessor.class).length);
t.write();
}
}
@@ -0,0 +1,17 @@
package com.ankurm.jpamig;
import com.ankurm.jpamig.domain.Book;
import com.ankurm.jpamig.repo.BookRepository;
import java.time.LocalDate;
final class Seed {
static void books(BookRepository repo) {
repo.deleteAllInBatch();
repo.save(new Book("Cosmos", null, "978-0001", "14.50", LocalDate.of(1980, 9, 1)));
repo.save(new Book("Dune", "Book one", "978-0002", "9.99", LocalDate.of(1965, 8, 1)));
repo.save(new Book("Emma", null, "978-0003", "7.25", LocalDate.of(1815, 12, 23)));
repo.save(new Book("Ficciones", "Stories", "978-0004", "12.00", LocalDate.of(1944, 1, 1)));
repo.save(new Book("Germinal", "Novel", "978-0005", "11.00", LocalDate.of(1885, 3, 1)));
SqlCapture.drain();
}
}
@@ -0,0 +1,50 @@
package com.ankurm.jpamig;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.springframework.boot.SpringBootVersion;
/** Writes ../output/NN-name-bootX.txt while the tests run, so every figure in the post comes from a build. */
public final class Transcript {
private final String name;
private final List<String> lines = new ArrayList<>();
public Transcript(String name) {
this.name = name;
lines.add("# Spring Boot " + SpringBootVersion.getVersion());
}
public void line(String s) {
lines.add(s);
}
public void sql() {
SqlCapture.drain().forEach(s -> lines.add(" SQL: " + s));
}
/** Runs the action and records either its value or the exception it threw. */
public void attempt(String label, Callable<?> action) {
try {
Object v = action.call();
lines.add(label + " -> " + v);
} catch (Throwable e) {
lines.add(label + " -> throws " + e.getClass().getName());
lines.add(" " + String.valueOf(e.getMessage()).lines().findFirst().orElse(""));
}
}
public void write() {
String major = SpringBootVersion.getVersion().substring(0, 1);
try {
Files.createDirectories(Path.of("../output"));
Files.write(Path.of("../output/" + name + "-boot" + major + ".txt"), lines);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,64 @@
package com.ankurm.jpamig;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Id;
import java.util.Arrays;
import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class WiringTest {
@Autowired ApplicationContext context;
static class NeedsEntityManager {
private final EntityManager em;
NeedsEntityManager(EntityManager anyName) {
this.em = anyName;
}
String describe() {
return em.toString().startsWith("Shared EntityManager proxy") ? "injected the shared proxy" : em.toString();
}
}
@Entity
record RecordEntity(@Id Long id, String title) {
}
@Test
void entityManagerBeansAndRecords() {
var t = new Transcript("08-wiring-and-records");
t.line("Spring Boot " + SpringBootVersion.getVersion()
+ ", Spring Data JPA " + org.springframework.data.jpa.repository.JpaRepository.class.getPackage().getImplementationVersion()
+ ", Hibernate " + org.hibernate.Version.getVersionString()
+ ", Java " + Runtime.version().feature());
String[] names = context.getBeanNamesForType(EntityManager.class);
t.line("beans of type EntityManager: " + Arrays.toString(names));
t.attempt("getBean(EntityManager.class) is a Spring shared proxy",
() -> context.getBean(EntityManager.class).toString().startsWith("Shared EntityManager proxy"));
t.attempt("create a bean with constructor parameter (EntityManager anyName)",
() -> context.getAutowireCapableBeanFactory().createBean(NeedsEntityManager.class).describe());
var cfg = new Configuration().addAnnotatedClass(RecordEntity.class)
.setProperty("hibernate.connection.url", "jdbc:h2:mem:rec")
.setProperty("hibernate.hbm2ddl.auto", "create-drop");
t.line("-- a record annotated @Entity");
try (var sf = cfg.buildSessionFactory()) {
t.line("buildSessionFactory() -> succeeded");
t.attempt("persist and commit", () -> {
sf.inTransaction(s -> s.persist(new RecordEntity(1L, "x")));
return "ok";
});
t.attempt("find by id in a new session", () -> sf.fromSession(s -> s.find(RecordEntity.class, 1L)));
} catch (Exception e) {
t.line("buildSessionFactory() -> throws " + e.getClass().getName() + ": " + e.getMessage());
}
t.write();
}
}
@@ -0,0 +1,19 @@
package com.ankurm.probe;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.math.BigDecimal;
@Entity
public class Item {
@Id Long id;
String title;
@Embedded Price price;
@Embeddable
public static class Price {
BigDecimal amount;
}
}
@@ -0,0 +1,13 @@
package com.ankurm.probe;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ItemRepository extends JpaRepository<Item, Long> {
/** "amount" is not a property of Item (it is price.amount), so this projection cannot be derived. */
record TitleAmount(String title, java.math.BigDecimal amount) {
}
List<TitleAmount> findByTitle(String title);
}
@@ -0,0 +1,7 @@
package com.ankurm.probe;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProbeApplication {
}
@@ -0,0 +1,58 @@
== spring-data-commons: spring-data-commons-3.5.13.jar -> spring-data-commons-4.2.0.jar
moved:
org.springframework.data.mapping.PropertyPath -> org.springframework.data.core.PropertyPath
org.springframework.data.mapping.PropertyReferenceException -> org.springframework.data.core.PropertyReferenceException
org.springframework.data.repository.util.ReactiveWrappers -> org.springframework.data.core.ReactiveWrappers
org.springframework.data.util.ClassTypeInformation -> org.springframework.data.core.ClassTypeInformation
org.springframework.data.util.CustomCollectionRegistrar -> org.springframework.data.core.CustomCollectionRegistrar
org.springframework.data.util.CustomCollections -> org.springframework.data.core.CustomCollections
org.springframework.data.util.NullableWrapper -> org.springframework.data.core.NullableWrapper
org.springframework.data.util.NullableWrapperConverters -> org.springframework.data.core.NullableWrapperConverters
org.springframework.data.util.ReactiveWrappers -> org.springframework.data.core.ReactiveWrappers
org.springframework.data.util.TypeDiscoverer -> org.springframework.data.core.TypeDiscoverer
org.springframework.data.util.TypeInformation -> org.springframework.data.core.TypeInformation
no type of the same name in the new jar:
org.springframework.data.annotation.PersistenceConstructor
org.springframework.data.mapping.model.DefaultSpELExpressionEvaluator
org.springframework.data.mapping.model.SpELExpressionEvaluator
org.springframework.data.mapping.model.SpELExpressionParameterValueProvider
org.springframework.data.repository.query.ExtensionAwareQueryMethodEvaluationContextProvider
org.springframework.data.repository.query.QueryMethodEvaluationContextProvider
org.springframework.data.repository.query.ReactiveExtensionAwareQueryMethodEvaluationContextProvider
org.springframework.data.repository.query.ReactiveQueryMethodEvaluationContextProvider
org.springframework.data.repository.query.SpelEvaluator
org.springframework.data.repository.query.SpelQueryContext
org.springframework.data.repository.util.ClassUtils
org.springframework.data.type.MethodsMetadata
org.springframework.data.type.classreading.MethodsMetadataReader
org.springframework.data.type.classreading.MethodsMetadataReaderFactory
org.springframework.data.util.CastUtils
== spring-data-jpa: spring-data-jpa-3.5.13.jar -> spring-data-jpa-4.2.0.jar
moved:
no type of the same name in the new jar:
org.springframework.data.jpa.repository.query.EmptyDeclaredQuery
org.springframework.data.jpa.repository.query.ExpressionBasedStringQuery
org.springframework.data.jpa.repository.query.JSqlParserUtils
org.springframework.data.jpa.repository.query.JpaQueryFactory
org.springframework.data.jpa.repository.query.QueryTransformers
org.springframework.data.jpa.repository.query.StringQuery
org.springframework.data.jpa.repository.support.QuerydslJpaRepository
== Boot types that tests and configuration import
-- boot3
org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest (spring-boot-test-autoconfigure-3.5.16.jar)
org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager (spring-boot-test-autoconfigure-3.5.16.jar)
org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase (spring-boot-test-autoconfigure-3.5.16.jar)
org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest (spring-boot-test-autoconfigure-3.5.16.jar)
org.springframework.boot.autoconfigure.domain.EntityScan (spring-boot-autoconfigure-3.5.16.jar)
org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer (spring-boot-autoconfigure-3.5.16.jar)
org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer (spring-boot-autoconfigure-3.5.16.jar)
JsonMapperBuilderCustomizer: not on this classpath
-- boot4
org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest (spring-boot-data-jpa-test-4.2.0.jar)
org.springframework.boot.jpa.test.autoconfigure.TestEntityManager (spring-boot-jpa-test-4.2.0.jar)
org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase (spring-boot-jdbc-test-4.2.0.jar)
org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest (spring-boot-webmvc-test-4.2.0.jar)
org.springframework.boot.persistence.autoconfigure.EntityScan (spring-boot-persistence-4.2.0.jar)
org.springframework.boot.hibernate.autoconfigure.HibernatePropertiesCustomizer (spring-boot-hibernate-4.2.0.jar)
Jackson2ObjectMapperBuilderCustomizer: not on this classpath
org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer (spring-boot-jackson-4.2.0.jar)
@@ -0,0 +1,15 @@
# Spring Boot 3.5.16
findByPriceAmountGreaterThan(8, title asc):
Cosmos
Dune
Ficciones
Germinal
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.amount>? order by b1_0.title
Query strings Hibernate statistics recorded for that call:
[CRITERIA] select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.amount>? order by b1_0.title
the same derived query with subtitle asc NULLS LAST -> throws java.lang.UnsupportedOperationException
Applying Null Precedence using Criteria Queries is not yet supported.
findByIsbn(missing) -> Optional.empty
findByTitleStartingWith("") with 5 rows -> throws org.springframework.dao.IncorrectResultSizeDataAccessException
Query did not return a unique result: 5 results were returned
@Query using || and left() -> Dune (978)
@@ -0,0 +1,15 @@
# Spring Boot 4.2.0
findByPriceAmountGreaterThan(8, title asc):
Cosmos
Dune
Ficciones
Germinal
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.amount>? order by b1_0.title
Query strings Hibernate statistics recorded for that call:
SELECT b FROM Book b INNER JOIN b.price p WHERE p.amount > :min ORDER BY b.title asc
the same derived query with subtitle asc NULLS LAST -> [Dune/Book one, Germinal/Novel, Ficciones/Stories, Cosmos/null]
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.amount>? order by b1_0.subtitle asc nulls last,b1_0.id
findByIsbn(missing) -> Optional.empty
findByTitleStartingWith("") with 5 rows -> throws org.springframework.dao.IncorrectResultSizeDataAccessException
Query did not return a unique result: 5 results were returned
@Query using || and left() -> Dune (978)
@@ -0,0 +1,4 @@
# Spring Boot 3.5.16
em.createQuery(...).getSingleResult() on no rows -> throws jakarta.persistence.NoResultException
No result found for query [select b from Book b where b.isbn = 'nope']
jakarta.persistence.TypedQuery declares getSingleResultOrNull() -> false
@@ -0,0 +1,4 @@
# Spring Boot 4.2.0
em.createQuery(...).getSingleResult() on no rows -> throws jakarta.persistence.NoResultException
No result found for query [select b from Book b where b.isbn = 'nope']
jakarta.persistence.TypedQuery declares getSingleResultOrNull() -> true
@@ -0,0 +1,10 @@
# Spring Boot 3.5.16
Hibernate 6.6.53.Final
native query column -> java.sql.Date
native query column -> java.time.OffsetDateTime
native query column -> java.sql.Time
read column 0 as java.sql.Date (old cast) -> 1965-08-01
save() of a new entity with a hand-assigned @GeneratedValue id -> throws org.springframework.orm.ObjectOptimisticLockingFailureException
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.ankurm.jpamig.domain.Book#4242]
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.id=?
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.id=?
@@ -0,0 +1,11 @@
# Spring Boot 4.2.0
Hibernate 7.4.15.Final
native query column -> java.time.LocalDate
native query column -> java.time.OffsetDateTime
native query column -> java.time.LocalTime
read column 0 as java.sql.Date (old cast) -> throws java.lang.ClassCastException
class java.time.LocalDate cannot be cast to class java.sql.Date (java.time.LocalDate is in module java.base of loader 'bootstrap'; java.sql.Date is in module java.sql of loader 'platform')
save() of a new entity with a hand-assigned @GeneratedValue id -> throws org.springframework.orm.ObjectOptimisticLockingFailureException
Row was already updated or deleted by another transaction for entity [com.ankurm.jpamig.domain.Book with id '4242']
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.id=?
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.id=?
@@ -0,0 +1,7 @@
# Spring Boot 3.5.16
count(publishedBefore 1900) -> 2
count(titleContains(null) i.e. unrestricted) -> 5
spec.and((Specification) null) -> 2
Specification.where((Specification) null) -> 5
findBy(spec, fluent).count -> 2
Querydsl findAll(price > 10, title asc) -> [Cosmos, Ficciones, Germinal]
@@ -0,0 +1,9 @@
# Spring Boot 4.2.0
count(publishedBefore 1900) -> 2
count(titleContains(null) i.e. unrestricted) -> 5
spec.and((Specification) null) -> throws java.lang.IllegalArgumentException
Other specification must not be null
Specification.where((Specification) null) -> throws java.lang.IllegalArgumentException
Specification must not be null
findBy(spec, fluent).count -> 2
Querydsl findAll(price > 10, title asc) -> [Cosmos, Ficciones, Germinal]
@@ -0,0 +1,16 @@
# Spring Boot 3.5.16
-- ORDER BY title, id (both columns NOT NULL)
window 1: [Cosmos, Dune] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 order by b1_0.title,b1_0.id fetch first ? rows only
next position keys: {id=22, title=Dune}
window 2: [Emma, Ficciones] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.title>? or b1_0.title=? and b1_0.id>? order by b1_0.title,b1_0.id fetch first ? rows only
next position keys: {id=24, title=Ficciones}
window 3: [Germinal] hasNext=false
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.title>? or b1_0.title=? and b1_0.id>? order by b1_0.title,b1_0.id fetch first ? rows only
-- ORDER BY subtitle (nullable), id
window 1: [Cosmos, Emma] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 order by b1_0.subtitle,b1_0.id fetch first ? rows only
window 2: [] hasNext=false
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.subtitle>? or b1_0.subtitle is null and b1_0.id>? order by b1_0.subtitle,b1_0.id fetch first ? rows only
rows seen: 2 of 5 [Cosmos/null, Emma/null]
@@ -0,0 +1,18 @@
# Spring Boot 4.2.0
-- ORDER BY title, id (both columns NOT NULL)
window 1: [Cosmos, Dune] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 order by b1_0.title,b1_0.id fetch first ? rows only
next position keys: {id=22, title=Dune}
window 2: [Emma, Ficciones] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.title>? or b1_0.title=? and b1_0.id>? order by b1_0.title,b1_0.id fetch first ? rows only
next position keys: {id=24, title=Ficciones}
window 3: [Germinal] hasNext=false
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.title>? or b1_0.title=? and b1_0.id>? order by b1_0.title,b1_0.id fetch first ? rows only
-- ORDER BY subtitle (nullable), id
window 1: [Cosmos, Emma] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 order by b1_0.subtitle,b1_0.id fetch first ? rows only
window 2: [Dune, Germinal] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.subtitle is not null or b1_0.subtitle is null and b1_0.id>? order by b1_0.subtitle,b1_0.id fetch first ? rows only
window 3: [Ficciones] hasNext=false
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.subtitle>? or b1_0.subtitle=? and b1_0.id>? order by b1_0.subtitle,b1_0.id fetch first ? rows only
rows seen: 5 of 5 [Cosmos/null, Emma/null, Dune/Book one, Germinal/Novel, Ficciones/Stories]
@@ -0,0 +1,12 @@
# Spring Boot 3.5.16
-- package marked @org.springframework.lang.NonNullApi
Book findByIsbn(missing) -> throws org.springframework.dao.EmptyResultDataAccessException
Result must not be null
Book findByIsbn(null) -> throws java.lang.IllegalArgumentException
Parameter isbn in LegacyNullRepository.findByIsbn must not be null
-- package marked @org.jspecify.annotations.NullMarked
Book findByIsbn(missing) -> null
Book findByIsbn(null) -> null
@Nullable Book findFirstByTitle(missing) -> null
findBySubtitle(@Nullable null).size -> 2
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.subtitle is null
@@ -0,0 +1,14 @@
# Spring Boot 4.2.0
-- package marked @org.springframework.lang.NonNullApi
Book findByIsbn(missing) -> throws org.springframework.dao.EmptyResultDataAccessException
Result must not be null
Book findByIsbn(null) -> throws java.lang.IllegalArgumentException
Parameter isbn in LegacyNullRepository.findByIsbn(java.lang.String) must not be null
-- package marked @org.jspecify.annotations.NullMarked
Book findByIsbn(missing) -> throws org.springframework.dao.EmptyResultDataAccessException
Result must not be null
Book findByIsbn(null) -> throws java.lang.IllegalArgumentException
Parameter isbn in JSpecifyRepository.findByIsbn(java.lang.String) must not be null
@Nullable Book findFirstByTitle(missing) -> null
findBySubtitle(@Nullable null).size -> 2
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.subtitle is null
@@ -0,0 +1,10 @@
# Spring Boot 3.5.16
Spring Boot 3.5.16, Spring Data JPA 3.5.13, Hibernate 6.6.53.Final, Java 25
beans of type EntityManager: [jpaSharedEM_entityManagerFactory, jpaSharedEM_AWC_entityManagerFactory]
getBean(EntityManager.class) is a Spring shared proxy -> true
create a bean with constructor parameter (EntityManager anyName) -> injected the shared proxy
-- a record annotated @Entity
buildSessionFactory() -> succeeded
persist and commit -> ok
find by id in a new session -> throws org.hibernate.InstantiationException
No default constructor for entity 'com.ankurm.jpamig.WiringTest$RecordEntity'
@@ -0,0 +1,10 @@
# Spring Boot 4.2.0
Spring Boot 4.2.0, Spring Data JPA 4.2.0, Hibernate 7.4.15.Final, Java 25
beans of type EntityManager: [entityManagerFactory, jpaSharedEM_entityManagerFactory]
getBean(EntityManager.class) is a Spring shared proxy -> true
create a bean with constructor parameter (EntityManager anyName) -> injected the shared proxy
-- a record annotated @Entity
buildSessionFactory() -> succeeded
persist and commit -> ok
find by id in a new session -> throws org.hibernate.InstantiationException
No default constructor for entity 'com.ankurm.jpamig.WiringTest$RecordEntity'
@@ -0,0 +1,10 @@
# Spring Boot 3.5.16
GET /page
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"pageable":{"pageNumber":0,"pageSize":2,"sort":{"empty":false,"sorted":true,"unsorted":false},"offset":0,"paged":true,"unpaged":false},"last":false,"totalPages":3,"totalElements":5,"size":2,"number":0,"first":true,"sort":{"empty":false,"sorted":true,"unsorted":false},"numberOfElements":2,"empty":false}
GET /paged-model
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"page":{"size":2,"number":0,"totalElements":5,"totalPages":3}}
GET /slice
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"pageable":{"pageNumber":0,"pageSize":2,"sort":{"empty":false,"sorted":true,"unsorted":false},"offset":0,"paged":true,"unpaged":false},"size":2,"number":0,"first":true,"last":false,"sort":{"empty":false,"sorted":true,"unsorted":false},"numberOfElements":2,"empty":false}
GET /window
200 {"empty":false,"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"last":false}
log: WARN --- [o-auto-1-exec-1] ration$PageModule$WarningLoggingModifier : Serializing PageImpl instances as-is is not supported, meaning that there is no guarantee about the stability of the resulting JSON structure!
@@ -0,0 +1,10 @@
# Spring Boot 4.2.0
GET /page
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"empty":false,"first":true,"last":false,"number":0,"numberOfElements":2,"pageable":{"offset":0,"pageNumber":0,"pageSize":2,"paged":true,"sort":{"empty":false,"sorted":true,"unsorted":false},"unpaged":false},"size":2,"sort":{"empty":false,"sorted":true,"unsorted":false},"totalElements":5,"totalPages":3}
GET /paged-model
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"page":{"size":2,"number":0,"totalElements":5,"totalPages":3}}
GET /slice
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"empty":false,"first":true,"last":false,"number":0,"numberOfElements":2,"pageable":{"offset":0,"pageNumber":0,"pageSize":2,"paged":true,"sort":{"empty":false,"sorted":true,"unsorted":false},"unpaged":false},"size":2,"sort":{"empty":false,"sorted":true,"unsorted":false}}
GET /window
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"empty":false,"last":false}
log: WARN --- [o-auto-1-exec-1] ration$PageModule$WarningLoggingModifier : Serializing PageImpl instances as-is is not supported, meaning that there is no guarantee about the stability of the resulting JSON structure!
@@ -0,0 +1,7 @@
# Spring Boot 3.5.16
POST /books {"title":"Dune","copies":3,"signed":true}
200 {"title":"Dune","copies":3,"signed":true}
POST /books {"title":"Dune"}
200 {"title":"Dune","copies":0,"signed":false}
POST /books {"title":"Dune","copies":null,"signed":false}
200 {"title":"Dune","copies":0,"signed":false}
@@ -0,0 +1,7 @@
# Spring Boot 4.2.0
POST /books {"title":"Dune","copies":3,"signed":true}
200 {"title":"Dune","copies":3,"signed":true}
POST /books {"title":"Dune"}
400 {"timestamp":"...","status":400,"error":"Bad Request","path":"/books"}
POST /books {"title":"Dune","copies":null,"signed":false}
400 {"timestamp":"...","status":400,"error":"Bad Request","path":"/books"}
@@ -0,0 +1,4 @@
# Spring Boot 3.5.16
spring.data.web.pageable.serialization-mode=via-dto
GET /page
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"page":{"size":2,"number":0,"totalElements":5,"totalPages":3}}
@@ -0,0 +1,4 @@
# Spring Boot 4.2.0
spring.data.web.pageable.serialization-mode=via-dto
GET /page
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"page":{"size":2,"number":0,"totalElements":5,"totalPages":3}}
@@ -0,0 +1,5 @@
# Spring Boot 3.5.16
record BookTitle(title, isbn), derived -> [BookTitle[title=Cosmos, isbn=978-0001]]
SQL: select b1_0.title,b1_0.isbn from book b1_0 where b1_0.isbn like ? escape '\'
record BookAmount via @Query constructor expression -> BookAmount[title=Cosmos, amount=14.50]
SQL: select b1_0.title,b1_0.amount from book b1_0 where b1_0.isbn=?
@@ -0,0 +1,5 @@
# Spring Boot 4.2.0
record BookTitle(title, isbn), derived -> [BookTitle[title=Cosmos, isbn=978-0001]]
SQL: select b1_0.title,b1_0.isbn from book b1_0 where b1_0.isbn like ? escape '\'
record BookAmount via @Query constructor expression -> BookAmount[title=Cosmos, amount=14.50]
SQL: select b1_0.title,b1_0.amount from book b1_0 where b1_0.isbn=?
@@ -0,0 +1,3 @@
# Spring Boot 3.5.16
application startup -> FAILED
root cause org.springframework.data.mapping.PropertyReferenceException: No property 'amount' found for type 'Item'
@@ -0,0 +1,4 @@
# Spring Boot 4.2.0
application startup -> succeeded
first call of findByTitle("x") -> throws org.springframework.data.core.PropertyReferenceException
No property 'amount' found for type 'Item'
@@ -0,0 +1,6 @@
# Spring Boot 3.5.16
spring.jackson.use-jackson2-defaults=true
GET /page
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"pageable":{"pageNumber":0,"pageSize":2,"sort":{"empty":false,"sorted":true,"unsorted":false},"offset":0,"paged":true,"unpaged":false},"last":false,"totalPages":3,"totalElements":5,"size":2,"number":0,"first":true,"sort":{"empty":false,"sorted":true,"unsorted":false},"numberOfElements":2,"empty":false}
POST /books {"title":"Dune"}
200 {"title":"Dune","copies":0,"signed":false}
@@ -0,0 +1,6 @@
# Spring Boot 4.2.0
spring.jackson.use-jackson2-defaults=true
GET /page
200 {"content":[{"id":1,"title":"Cosmos","isbn":"978-0001","publishedOn":"1980-09-01"},{"id":2,"title":"Dune","isbn":"978-0002","publishedOn":"1965-08-01"}],"pageable":{"pageNumber":0,"pageSize":2,"sort":{"empty":false,"sorted":true,"unsorted":false},"offset":0,"paged":true,"unpaged":false},"last":false,"totalPages":3,"totalElements":5,"size":2,"number":0,"first":true,"sort":{"empty":false,"sorted":true,"unsorted":false},"numberOfElements":2,"empty":false}
POST /books {"title":"Dune"}
200 {"title":"Dune","copies":0,"signed":false}
@@ -0,0 +1,6 @@
# Spring Boot 3.5.16
window 1: [Dune, Germinal] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 order by b1_0.subtitle,b1_0.id fetch first ? rows only
window 2: [Ficciones] hasNext=false
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.subtitle>? or b1_0.subtitle=? and b1_0.id>? order by b1_0.subtitle,b1_0.id fetch first ? rows only
rows seen: 3 of 5 [Dune/Book one, Germinal/Novel, Ficciones/Stories]
@@ -0,0 +1,6 @@
# Spring Boot 4.2.0
window 1: [Dune, Germinal] hasNext=true
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 order by b1_0.subtitle,b1_0.id fetch first ? rows only
window 2: [Ficciones] hasNext=false
SQL: select b1_0.id,b1_0.isbn,b1_0.amount,b1_0.currency,b1_0.published_on,b1_0.subtitle,b1_0.title from book b1_0 where b1_0.subtitle>? or b1_0.subtitle=? and b1_0.id>? order by b1_0.subtitle,b1_0.id fetch first ? rows only
rows seen: 3 of 5 [Dune/Book one, Germinal/Novel, Ficciones/Stories]
@@ -0,0 +1,10 @@
# Spring Boot 3.5.16
window 1: [Dune, Germinal] hasNext=true
window 2: [Ficciones] hasNext=false
rows seen: 3 of 5 [Dune/Book one, Germinal/Novel, Ficciones/Stories]
-- same scroll with an explicit Sort: subtitle ASC NULLS_FIRST, id
rows seen -> throws java.lang.UnsupportedOperationException
Applying Null Precedence using Criteria Queries is not yet supported.
-- same scroll with an explicit Sort: subtitle ASC NULLS_LAST, id
rows seen -> throws java.lang.UnsupportedOperationException
Applying Null Precedence using Criteria Queries is not yet supported.
@@ -0,0 +1,8 @@
# Spring Boot 4.2.0
window 1: [Dune, Germinal] hasNext=true
window 2: [Ficciones] hasNext=false
rows seen: 3 of 5 [Dune/Book one, Germinal/Novel, Ficciones/Stories]
-- same scroll with an explicit Sort: subtitle ASC NULLS_FIRST, id
rows seen -> 5 of 5 [Cosmos/null, Emma/null, Dune/Book one, Germinal/Novel, Ficciones/Stories]
-- same scroll with an explicit Sort: subtitle ASC NULLS_LAST, id
rows seen -> 5 of 5 [Dune/Book one, Germinal/Novel, Ficciones/Stories, Cosmos/null, Emma/null]
@@ -0,0 +1,81 @@
--- boot3
+++ boot4
@@ -12,18 +12,27 @@
void deleteInBatch(Iterable<T>) @Deprecated
void flush()
== org.springframework.data.jpa.repository.JpaSpecificationExecutor
+ List<T> findAll(PredicateSpecification<T>)
List<T> findAll(Specification<T>)
List<T> findAll(Specification<T>, Sort)
+ Optional<T> findOne(PredicateSpecification<T>)
Optional<T> findOne(Specification<T>)
Page<T> findAll(Specification<T>, Pageable)
Page<T> findAll(Specification<T>, Specification<T>, Pageable)
+ R findBy(PredicateSpecification<T>, Function<? super JpaSpecificationExecutor.SpecificationFluentQuery<S>, R>)
R findBy(Specification<T>, Function<? super JpaSpecificationExecutor.SpecificationFluentQuery<S>, R>)
+ boolean exists(PredicateSpecification<T>)
boolean exists(Specification<T>)
+ long count(PredicateSpecification<T>)
long count(Specification<T>)
- long delete(Specification<T>)
+ long delete(DeleteSpecification<T>)
+ long delete(PredicateSpecification<T>)
+ long update(UpdateSpecification<T>)
== org.springframework.data.jpa.domain.Specification
Predicate toPredicate(Root<T>, CriteriaQuery<?>, CriteriaBuilder)
+ Specification<T> and(PredicateSpecification<T>)
Specification<T> and(Specification<T>)
+ Specification<T> or(PredicateSpecification<T>)
Specification<T> or(Specification<T>)
static Specification<T> allOf(Iterable<Specification<T>>)
static Specification<T> allOf(Specification<T>[])
@@ -31,10 +40,45 @@
static Specification<T> anyOf(Specification<T>[])
static Specification<T> not(Specification<T>)
static Specification<T> unrestricted()
- static Specification<T> where(Specification<T>) @Deprecated
+ static Specification<T> where(PredicateSpecification<T>)
+ static Specification<T> where(Specification<T>)
== org.springframework.data.jpa.domain.PredicateSpecification
- NOT ON THIS CLASSPATH
+ Predicate toPredicate(From<?, T>, CriteriaBuilder)
+ PredicateSpecification<T> and(PredicateSpecification<T>)
+ PredicateSpecification<T> or(PredicateSpecification<T>)
+ static PredicateSpecification<T> allOf(Iterable<PredicateSpecification<T>>)
+ static PredicateSpecification<T> allOf(PredicateSpecification<T>[])
+ static PredicateSpecification<T> anyOf(Iterable<PredicateSpecification<T>>)
+ static PredicateSpecification<T> anyOf(PredicateSpecification<T>[])
+ static PredicateSpecification<T> not(PredicateSpecification<T>)
+ static PredicateSpecification<T> unrestricted()
+ static PredicateSpecification<T> where(PredicateSpecification<T>)
== org.springframework.data.jpa.domain.DeleteSpecification
- NOT ON THIS CLASSPATH
+ DeleteSpecification<T> and(DeleteSpecification<T>)
+ DeleteSpecification<T> and(PredicateSpecification<T>)
+ DeleteSpecification<T> or(DeleteSpecification<T>)
+ DeleteSpecification<T> or(PredicateSpecification<T>)
+ Predicate toPredicate(Root<T>, CriteriaDelete<T>, CriteriaBuilder)
+ static DeleteSpecification<T> allOf(DeleteSpecification<T>[])
+ static DeleteSpecification<T> allOf(Iterable<DeleteSpecification<T>>)
+ static DeleteSpecification<T> anyOf(DeleteSpecification<T>[])
+ static DeleteSpecification<T> anyOf(Iterable<DeleteSpecification<T>>)
+ static DeleteSpecification<T> not(DeleteSpecification<T>)
+ static DeleteSpecification<T> unrestricted()
+ static DeleteSpecification<T> where(DeleteSpecification<T>)
+ static DeleteSpecification<T> where(PredicateSpecification<T>)
== org.springframework.data.jpa.domain.UpdateSpecification
- NOT ON THIS CLASSPATH
+ Predicate toPredicate(Root<T>, CriteriaUpdate<T>, CriteriaBuilder)
+ UpdateSpecification<T> and(PredicateSpecification<T>)
+ UpdateSpecification<T> and(UpdateSpecification<T>)
+ UpdateSpecification<T> or(PredicateSpecification<T>)
+ UpdateSpecification<T> or(UpdateSpecification<T>)
+ static UpdateSpecification.UpdateOperation<T> update(UpdateSpecification.UpdateOperation<T>)
+ static UpdateSpecification<T> allOf(Iterable<UpdateSpecification<T>>)
+ static UpdateSpecification<T> allOf(UpdateSpecification<T>[])
+ static UpdateSpecification<T> anyOf(Iterable<UpdateSpecification<T>>)
+ static UpdateSpecification<T> anyOf(UpdateSpecification<T>[])
+ static UpdateSpecification<T> not(UpdateSpecification<T>)
+ static UpdateSpecification<T> unrestricted()
+ static UpdateSpecification<T> where(PredicateSpecification<T>)
+ static UpdateSpecification<T> where(UpdateSpecification<T>)
@@ -0,0 +1,84 @@
== org.springframework.data.jpa.repository.JpaRepository
List<S> findAll(Example<S>)
List<S> findAll(Example<S>, Sort)
List<S> saveAllAndFlush(Iterable<S>)
S saveAndFlush(S)
T getById(ID) @Deprecated
T getOne(ID) @Deprecated
T getReferenceById(ID)
void deleteAllByIdInBatch(Iterable<ID>)
void deleteAllInBatch()
void deleteAllInBatch(Iterable<T>)
void deleteInBatch(Iterable<T>) @Deprecated
void flush()
== org.springframework.data.jpa.repository.JpaSpecificationExecutor
List<T> findAll(PredicateSpecification<T>)
List<T> findAll(Specification<T>)
List<T> findAll(Specification<T>, Sort)
Optional<T> findOne(PredicateSpecification<T>)
Optional<T> findOne(Specification<T>)
Page<T> findAll(Specification<T>, Pageable)
Page<T> findAll(Specification<T>, Specification<T>, Pageable)
R findBy(PredicateSpecification<T>, Function<? super JpaSpecificationExecutor.SpecificationFluentQuery<S>, R>)
R findBy(Specification<T>, Function<? super JpaSpecificationExecutor.SpecificationFluentQuery<S>, R>)
boolean exists(PredicateSpecification<T>)
boolean exists(Specification<T>)
long count(PredicateSpecification<T>)
long count(Specification<T>)
long delete(DeleteSpecification<T>)
long delete(PredicateSpecification<T>)
long update(UpdateSpecification<T>)
== org.springframework.data.jpa.domain.Specification
Predicate toPredicate(Root<T>, CriteriaQuery<?>, CriteriaBuilder)
Specification<T> and(PredicateSpecification<T>)
Specification<T> and(Specification<T>)
Specification<T> or(PredicateSpecification<T>)
Specification<T> or(Specification<T>)
static Specification<T> allOf(Iterable<Specification<T>>)
static Specification<T> allOf(Specification<T>[])
static Specification<T> anyOf(Iterable<Specification<T>>)
static Specification<T> anyOf(Specification<T>[])
static Specification<T> not(Specification<T>)
static Specification<T> unrestricted()
static Specification<T> where(PredicateSpecification<T>)
static Specification<T> where(Specification<T>)
== org.springframework.data.jpa.domain.PredicateSpecification
Predicate toPredicate(From<?, T>, CriteriaBuilder)
PredicateSpecification<T> and(PredicateSpecification<T>)
PredicateSpecification<T> or(PredicateSpecification<T>)
static PredicateSpecification<T> allOf(Iterable<PredicateSpecification<T>>)
static PredicateSpecification<T> allOf(PredicateSpecification<T>[])
static PredicateSpecification<T> anyOf(Iterable<PredicateSpecification<T>>)
static PredicateSpecification<T> anyOf(PredicateSpecification<T>[])
static PredicateSpecification<T> not(PredicateSpecification<T>)
static PredicateSpecification<T> unrestricted()
static PredicateSpecification<T> where(PredicateSpecification<T>)
== org.springframework.data.jpa.domain.DeleteSpecification
DeleteSpecification<T> and(DeleteSpecification<T>)
DeleteSpecification<T> and(PredicateSpecification<T>)
DeleteSpecification<T> or(DeleteSpecification<T>)
DeleteSpecification<T> or(PredicateSpecification<T>)
Predicate toPredicate(Root<T>, CriteriaDelete<T>, CriteriaBuilder)
static DeleteSpecification<T> allOf(DeleteSpecification<T>[])
static DeleteSpecification<T> allOf(Iterable<DeleteSpecification<T>>)
static DeleteSpecification<T> anyOf(DeleteSpecification<T>[])
static DeleteSpecification<T> anyOf(Iterable<DeleteSpecification<T>>)
static DeleteSpecification<T> not(DeleteSpecification<T>)
static DeleteSpecification<T> unrestricted()
static DeleteSpecification<T> where(DeleteSpecification<T>)
static DeleteSpecification<T> where(PredicateSpecification<T>)
== org.springframework.data.jpa.domain.UpdateSpecification
Predicate toPredicate(Root<T>, CriteriaUpdate<T>, CriteriaBuilder)
UpdateSpecification<T> and(PredicateSpecification<T>)
UpdateSpecification<T> and(UpdateSpecification<T>)
UpdateSpecification<T> or(PredicateSpecification<T>)
UpdateSpecification<T> or(UpdateSpecification<T>)
static UpdateSpecification.UpdateOperation<T> update(UpdateSpecification.UpdateOperation<T>)
static UpdateSpecification<T> allOf(Iterable<UpdateSpecification<T>>)
static UpdateSpecification<T> allOf(UpdateSpecification<T>[])
static UpdateSpecification<T> anyOf(Iterable<UpdateSpecification<T>>)
static UpdateSpecification<T> anyOf(UpdateSpecification<T>[])
static UpdateSpecification<T> not(UpdateSpecification<T>)
static UpdateSpecification<T> unrestricted()
static UpdateSpecification<T> where(PredicateSpecification<T>)
static UpdateSpecification<T> where(UpdateSpecification<T>)
@@ -0,0 +1,123 @@
=== DeleteBySpecification.java on boot3
compiles
=== DeleteBySpecification.java on boot4
DOES NOT COMPILE
broken/boot3-style/DeleteBySpecification.java:7: error: no suitable method found for delete(Specification<Book>)
1 error
=== HibernateSessionApi.java on boot3
compiles
broken/boot3-style/HibernateSessionApi.java:6: warning: [deprecation] Where in org.hibernate.annotations has been deprecated
broken/boot3-style/HibernateSessionApi.java:10: warning: [deprecation] save(Object) in Session has been deprecated
broken/boot3-style/HibernateSessionApi.java:11: warning: [deprecation] saveOrUpdate(Object) in Session has been deprecated
broken/boot3-style/HibernateSessionApi.java:12: warning: [deprecation] update(Object) in Session has been deprecated
broken/boot3-style/HibernateSessionApi.java:13: warning: [deprecation] delete(Object) in Session has been deprecated
5 warnings
=== HibernateSessionApi.java on boot4
DOES NOT COMPILE
broken/boot3-style/HibernateSessionApi.java:3: error: cannot find symbol
symbol: class Where
location: package org.hibernate.annotations
broken/boot3-style/HibernateSessionApi.java:6: error: cannot find symbol
symbol: class Where
location: class HibernateSessionApi
broken/boot3-style/HibernateSessionApi.java:10: error: cannot find symbol
symbol: method save(Book)
location: variable session of type Session
broken/boot3-style/HibernateSessionApi.java:11: error: cannot find symbol
symbol: method saveOrUpdate(Book)
location: variable session of type Session
broken/boot3-style/HibernateSessionApi.java:12: error: cannot find symbol
symbol: method update(Book)
location: variable session of type Session
broken/boot3-style/HibernateSessionApi.java:13: error: cannot find symbol
symbol: method delete(Book)
location: variable session of type Session
6 errors
=== JacksonCustomizer.java on boot3
compiles
=== JacksonCustomizer.java on boot4
DOES NOT COMPILE
broken/boot3-style/JacksonCustomizer.java:1: error: package org.springframework.boot.autoconfigure.jackson does not exist
broken/boot3-style/JacksonCustomizer.java:4: error: cannot find symbol
symbol: class Jackson2ObjectMapperBuilderCustomizer
location: class JacksonCustomizer
2 errors
=== PackageMoves.java on boot3
compiles
=== PackageMoves.java on boot4
DOES NOT COMPILE
broken/boot3-style/PackageMoves.java:1: error: cannot find symbol
symbol: class PropertyPath
location: package org.springframework.data.mapping
broken/boot3-style/PackageMoves.java:2: error: cannot find symbol
symbol: class PropertyReferenceException
location: package org.springframework.data.mapping
broken/boot3-style/PackageMoves.java:3: error: cannot find symbol
symbol: class TypeInformation
location: package org.springframework.data.util
broken/boot3-style/PackageMoves.java:6: error: cannot find symbol
symbol: class TypeInformation
location: class PackageMoves
broken/boot3-style/PackageMoves.java:7: error: cannot find symbol
symbol: class PropertyPath
location: class PackageMoves
broken/boot3-style/PackageMoves.java:8: error: cannot find symbol
symbol: class PropertyReferenceException
location: class PackageMoves
broken/boot3-style/PackageMoves.java:6: error: cannot find symbol
symbol: variable TypeInformation
location: class PackageMoves
7 errors
=== QueryDslPaging.java on boot3
compiles
broken/boot3-style/QueryDslPaging.java:5: warning: [deprecation] QPageRequest(int,int) in QPageRequest has been deprecated
1 warning
=== QueryDslPaging.java on boot4
DOES NOT COMPILE
broken/boot3-style/QueryDslPaging.java:5: error: QPageRequest(int,int,OrderSpecifier<?>...) has private access in QPageRequest
1 error
=== RemovedAnnotations.java on boot3
compiles
broken/boot3-style/RemovedAnnotations.java:4: warning: [removal] PersistenceConstructor in org.springframework.data.annotation has been deprecated and marked for removal
1 warning
=== RemovedAnnotations.java on boot4
DOES NOT COMPILE
broken/boot3-style/RemovedAnnotations.java:1: error: cannot find symbol
symbol: class PersistenceConstructor
location: package org.springframework.data.annotation
broken/boot3-style/RemovedAnnotations.java:4: error: cannot find symbol
symbol: class PersistenceConstructor
location: class RemovedAnnotations
2 errors
=== StillCompiles.java on boot3
compiles
broken/boot3-style/StillCompiles.java:7: warning: [deprecation] getOne(ID) in JpaRepository has been deprecated
broken/boot3-style/StillCompiles.java:8: warning: [deprecation] getById(ID) in JpaRepository has been deprecated
broken/boot3-style/StillCompiles.java:9: warning: [deprecation] deleteInBatch(Iterable<T>) in JpaRepository has been deprecated
3 warnings
=== StillCompiles.java on boot4
compiles
broken/boot3-style/StillCompiles.java:7: warning: [deprecation] getOne(ID) in JpaRepository has been deprecated
broken/boot3-style/StillCompiles.java:8: warning: [deprecation] getById(ID) in JpaRepository has been deprecated
broken/boot3-style/StillCompiles.java:9: warning: [deprecation] deleteInBatch(Iterable<T>) in JpaRepository has been deprecated
3 warnings
=== TestSliceImports.java on boot3
compiles
=== TestSliceImports.java on boot4
DOES NOT COMPILE
broken/boot3-style/TestSliceImports.java:1: error: package org.springframework.boot.autoconfigure.domain does not exist
broken/boot3-style/TestSliceImports.java:2: error: cannot find symbol
symbol: class AutoConfigureTestDatabase
location: package org.springframework.boot.test.autoconfigure.jdbc
broken/boot3-style/TestSliceImports.java:3: error: package org.springframework.boot.test.autoconfigure.orm.jpa does not exist
broken/boot3-style/TestSliceImports.java:4: error: package org.springframework.boot.test.autoconfigure.orm.jpa does not exist
broken/boot3-style/TestSliceImports.java:5: error: package org.springframework.boot.test.autoconfigure.web.servlet does not exist
5 errors
=== WhereNull.java on boot3
compiles
broken/boot3-style/WhereNull.java:6: warning: [removal] <T>where(Specification<T>) in Specification has been deprecated and marked for removal
1 warning
=== WhereNull.java on boot4
DOES NOT COMPILE
broken/boot3-style/WhereNull.java:6: error: reference to where is ambiguous
1 error
@@ -0,0 +1,10 @@
=== old artifactId hibernate-jpamodelgen, version ${hibernate.version}
BUILD SUCCESS
Book_ generated: 1 file(s)
=== old artifactId hibernate-jpamodelgen, no <version> (relying on Boot's BOM)
BUILD FAILURE
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.16.0:compile (default-compile) on project data-jpa-3-to-4-boot4: Resolution of annotationProcessorPath dependencies failed: Cannot find version for annotation processor path 'org.hibernate.orm:hibernate-jpamodelgen.jar'. The version needs to be either provided directly in the plugin configuration or via dependency mana
Book_ generated: 0 file(s)
=== new artifactId hibernate-processor, no <version>
BUILD SUCCESS
Book_ generated: 1 file(s)
+11
View File
@@ -0,0 +1,11 @@
=== com.querydsl 5.1.0 + record @Embeddable, Boot 3.5
BUILD FAILURE
Fatal error compiling: java.lang.IllegalArgumentException: Illegal type: com.ankurm.jpamig.domain.Amount -> [Help 1]
=== com.querydsl 5.1.0 + record @Embeddable, Boot 4.2
BUILD FAILURE
Fatal error compiling: java.lang.IllegalArgumentException: Illegal type: com.ankurm.jpamig.domain.Amount -> [Help 1]
=== io.github.openfeign.querydsl 7.8 + record @Embeddable, Boot 4.2
BUILD SUCCESS
=== io.github.openfeign.querydsl 7.8, whole test suite, Boot 4.2
BUILD SUCCESS
[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 1
@@ -0,0 +1,5 @@
spring-data-jpa-3.5.13.jar: class files containing the string spring.data.jpa.query.native.parser: 1
spring-data-jpa-4.2.0.jar: class files containing the string spring.data.jpa.query.native.parser: 0
=== how 3.5 reads it (javap -c)
ldc // String spring.data.jpa.query.native.parser
invokestatic // Method org/springframework/core/SpringProperties.getProperty:(Ljava/lang/String;)Ljava/lang/String;
@@ -0,0 +1,3 @@
# Spring Boot 3.5.16
books.delete(specification) -> 2
SQL: delete from book b1_0 where b1_0.published_on<?
@@ -0,0 +1,7 @@
# Spring Boot 4.2.0
books.count(predicate) -> 2
SQL: select count(b1_0.id) from book b1_0 where b1_0.published_on<?
books.update(UpdateSpecification) -> 1
SQL: update book b1_0 set title=? where b1_0.title=?
books.delete(predicate) -> 2
SQL: delete from book b1_0 where b1_0.published_on<?
@@ -0,0 +1,3 @@
# Spring Boot 3.5.16
spring.dao.exceptiontranslation.enabled=false
PersistenceExceptionTranslationPostProcessor beans: 0
@@ -0,0 +1,3 @@
# Spring Boot 4.2.0
spring.dao.exceptiontranslation.enabled=false
PersistenceExceptionTranslationPostProcessor beans: 1
@@ -0,0 +1,5 @@
# Spring Boot 3.5.16
hibernate.query.native.prefer_jdbc_datetime_types=true
native query column -> java.sql.Date
native query column -> java.time.OffsetDateTime
native query column -> java.sql.Time
@@ -0,0 +1,5 @@
# Spring Boot 4.2.0
hibernate.query.native.prefer_jdbc_datetime_types=true
native query column -> java.sql.Date
native query column -> java.time.OffsetDateTime
native query column -> java.sql.Time
+36
View File
@@ -0,0 +1,36 @@
import java.lang.reflect.*;
import java.util.*;
import java.util.stream.*;
/**
* Prints the public methods each named type declares, flagging {@code @Deprecated} ones.
* Run it once per classpath (Boot 3.5 and Boot 4) and diff the two files.
* Usage: java -cp "$(cat cp.txt)" ApiDump.java org.springframework.data.jpa.repository.JpaRepository ...
*/
public class ApiDump {
public static void main(String[] args) {
for (String name : args) {
System.out.println("== " + name);
try {
Class<?> c = Class.forName(name, false, Thread.currentThread().getContextClassLoader());
if (c.isAnnotationPresent(Deprecated.class)) System.out.println(" (type is @Deprecated)");
Arrays.stream(c.getDeclaredMethods())
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic() && !m.isBridge())
.map(m -> " " + sig(m) + (m.isAnnotationPresent(Deprecated.class) ? " @Deprecated" : ""))
.sorted().forEach(System.out::println);
} catch (ClassNotFoundException e) {
System.out.println(" NOT ON THIS CLASSPATH");
}
}
}
static String sig(Method m) {
return (Modifier.isStatic(m.getModifiers()) ? "static " : "")
+ simple(m.getGenericReturnType()) + " " + m.getName() + "("
+ Arrays.stream(m.getGenericParameterTypes()).map(ApiDump::simple).collect(Collectors.joining(", ")) + ")";
}
static String simple(Type t) {
return t.getTypeName().replaceAll("[a-z][\\w]*\\.", "").replace('$', '.');
}
}
+14
View File
@@ -0,0 +1,14 @@
"""Prints the fully qualified name and jar of each simple type name found on a classpath file."""
import sys
import zipfile
wanted = sys.argv[2:]
found = {}
for jar in open(sys.argv[1]).read().strip().split(':'):
for n in zipfile.ZipFile(jar).namelist():
simple = n.rsplit('/', 1)[-1][:-6]
if n.endswith('.class') and n.startswith('org/springframework/boot/') and simple in wanted:
found.setdefault(simple, []).append('%s (%s)' % (n[:-6].replace('/', '.'), jar.rsplit('/', 1)[1]))
for w in wanted:
for line in found.get(w, ['%s: not on this classpath' % w]):
print(' ' + line)
+7
View File
@@ -0,0 +1,7 @@
"""Counts class files in a jar whose bytes contain a string."""
import sys
import zipfile
z = zipfile.ZipFile(sys.argv[1])
needle = sys.argv[2].encode()
print(sum(1 for n in z.namelist() if n.endswith('.class') and needle in z.read(n)))
+24
View File
@@ -0,0 +1,24 @@
"""Top-level types that vanished between two jars, split into 'moved' (same simple name elsewhere) and 'gone'."""
import collections
import sys
import zipfile
def classes(path):
return {n[:-6].replace('/', '.') for n in zipfile.ZipFile(path).namelist()
if n.endswith('.class') and not n.startswith('META-INF') and 'package-info' not in n and '$' not in n}
old, new = classes(sys.argv[1]), classes(sys.argv[2])
added = collections.defaultdict(list)
for c in new - old:
added[c.rsplit('.', 1)[1]].append(c)
gone = sorted(old - new)
print('moved:')
for c in gone:
if c.rsplit('.', 1)[1] in added:
print(' %s -> %s' % (c, ', '.join(sorted(added[c.rsplit('.', 1)[1]]))))
print('no type of the same name in the new jar:')
for c in gone:
if c.rsplit('.', 1)[1] not in added:
print(' ' + c)
+12
View File
@@ -0,0 +1,12 @@
"""Edits a copy of boot4/pom.xml to use the OpenFeign fork of Querydsl instead of com.querydsl."""
import sys
VERSION = '7.8'
path = sys.argv[1]
s = open(path).read()
s = s.replace('<groupId>com.querydsl</groupId>', '<groupId>io.github.openfeign.querydsl</groupId>')
s = s.replace('<artifactId>querydsl-jpa</artifactId>\n <version>${querydsl.version}</version>\n <classifier>jakarta</classifier>',
'<artifactId>querydsl-jpa</artifactId>\n <version>%s</version>' % VERSION)
s = s.replace('<artifactId>querydsl-apt</artifactId>\n <version>${querydsl.version}</version>',
'<artifactId>querydsl-apt</artifactId>\n <version>%s</version>' % VERSION)
open(path, 'w').write(s)
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env bash
# Regenerates every file in ../output. Needs JDK 25 and Maven on the PATH.
# Optional: PG_URL=jdbc:postgresql://localhost:5432/postgres PG_USER=postgres PG_PASSWORD=... for output 16.
set -eu
cd "$(dirname "$0")/.."
MODULE="$PWD"
OUT="$MODULE/output"
mkdir -p "$OUT"
WORK="$(mktemp -d)"
PG_ARGS=()
if [ -n "${PG_URL:-}" ]; then
PG_ARGS=(-Dpg.url="$PG_URL" -Dpg.user="${PG_USER:-postgres}" -Dpg.password="${PG_PASSWORD:-}")
fi
echo "== tests on both generations (they write output/02..16)"
for g in boot3 boot4; do
(cd "$g" && mvn -B -q clean test "${PG_ARGS[@]}")
(cd "$g" && mvn -B -q dependency:build-classpath -Dmdep.outputFile="$WORK/cp-$g.txt")
done
scrub() { sed -e "s#$MODULE/##g" -e "s#$WORK#<tmp>#g" -e "s#$HOME#~#g" -e '/^Picked up /d'; }
cp_of() { cat "$WORK/cp-$1.txt"; }
jar_of() { tr ':' '\n' < "$WORK/cp-$1.txt" | grep "/$2-[0-9][^/]*\.jar$" | head -1; }
echo "== 01 package moves and removals, read from the jars"
{
for a in spring-data-commons spring-data-jpa; do
echo "== $a: $(basename "$(jar_of boot3 $a)") -> $(basename "$(jar_of boot4 $a)")"
python3 -I scripts/jar_moves.py "$(jar_of boot3 $a)" "$(jar_of boot4 $a)"
done
echo "== Boot types that tests and configuration import"
for g in boot3 boot4; do
echo "-- $g"
python3 -I scripts/find_types.py "$WORK/cp-$g.txt" DataJpaTest TestEntityManager AutoConfigureTestDatabase \
WebMvcTest EntityScan HibernatePropertiesCustomizer Jackson2ObjectMapperBuilderCustomizer JsonMapperBuilderCustomizer
done
} > "$OUT/01-package-moves.txt"
echo "== 17 public repository API on both generations"
J=org.springframework.data.jpa
TYPES="$J.repository.JpaRepository $J.repository.JpaSpecificationExecutor $J.domain.Specification \
$J.domain.PredicateSpecification $J.domain.DeleteSpecification $J.domain.UpdateSpecification"
for g in boot3 boot4; do
java -cp "$(cp_of $g)" scripts/ApiDump.java $TYPES 2>/dev/null > "$WORK/api-$g.txt"
done
{ diff -u --label boot3 --label boot4 "$WORK/api-boot3.txt" "$WORK/api-boot4.txt" || true; } > "$OUT/17-repository-api.diff.txt"
cp "$WORK/api-boot4.txt" "$OUT/18-repository-api-boot4.txt"
echo "== 19 Boot 3 style sources against both classpaths"
{
for f in broken/boot3-style/*.java; do
for g in boot3 boot4; do
mkdir -p "$WORK/classes"
echo "=== $(basename "$f") on $g"
if javac -proc:none -Xlint:deprecation,removal -Xmaxerrs 20 -d "$WORK/classes" \
-cp "$g/target/classes:$(cp_of $g)" "$f" > "$WORK/javac.txt" 2>&1; then
echo "compiles"
else
echo "DOES NOT COMPILE"
fi
scrub < "$WORK/javac.txt" | grep -E 'error:|warning:|symbol:|location:|^[0-9]+ (error|warning)' || true
done
done
} > "$OUT/19-compile-errors.txt"
echo "== 20 the metamodel processor coordinate on Boot 4"
{
variant() { # $1 label, $2 python expression that edits the pom
d="$WORK/variant-$3"; mkdir -p "$d/boot4"
cp -r common "$d/"; cp boot4/pom.xml "$d/boot4/"
python3 -I -c "import sys;p=sys.argv[1];s=open(p).read();$2;open(p,'w').write(s)" "$d/boot4/pom.xml"
echo "=== $1"
if (cd "$d/boot4" && mvn -B clean compile > mvn.log 2>&1); then echo "BUILD SUCCESS"; else echo "BUILD FAILURE"; fi
grep -E 'relocat|has been relocated|^\[ERROR\] (Failed|.*cannot find symbol|.*Resolution)|version can neither|version is missing' "$d/boot4/mvn.log" \
| sed -e "s#$d/##g" | scrub | cut -c1-400 | sort -u | head -8
echo "Book_ generated: $(find "$d/boot4/target" -name 'Book_.java' 2>/dev/null | wc -l) file(s)"
}
OLD="s=s.replace('<artifactId>hibernate-processor</artifactId>','<artifactId>hibernate-jpamodelgen</artifactId>')"
variant "old artifactId hibernate-jpamodelgen, version \${hibernate.version}" "$OLD" a
variant "old artifactId hibernate-jpamodelgen, no <version> (relying on Boot's BOM)" \
"$OLD;s=s.replace('<artifactId>hibernate-jpamodelgen</artifactId>\n <version>\${hibernate.version}</version>','<artifactId>hibernate-jpamodelgen</artifactId>')" b
variant "new artifactId hibernate-processor, no <version>" \
"s=s.replace('<artifactId>hibernate-processor</artifactId>\n <version>\${hibernate.version}</version>','<artifactId>hibernate-processor</artifactId>')" c
} > "$OUT/20-metamodel-processor.txt"
echo "== 21 querydsl and a record @Embeddable, then the OpenFeign fork on Boot 4"
{
qd() { # $1 label, $2 generation, $3 'openfeign' or empty, $4 'record' or empty, $5 maven goal
d="$(mktemp -d "$WORK/qd-XXXX")"; cp -r common "$d/"; mkdir -p "$d/$2" "$d/output"; cp "$2/pom.xml" "$d/$2/"
[ "$3" = openfeign ] && python3 -I scripts/openfeign.py "$d/$2/pom.xml"
[ "$4" = record ] && { echo "package com.ankurm.jpamig.domain;"; cat broken/querydsl-record/Invoice.java; } \
> "$d/common/src/main/java/com/ankurm/jpamig/domain/Invoice.java"
echo "=== $1"
if (cd "$d/$2" && mvn -B clean $5 > mvn.log 2>&1); then echo "BUILD SUCCESS"; else echo "BUILD FAILURE"; fi
grep -E 'Fatal error compiling|Tests run: [0-9]+, F[^-]*$' "$d/$2/mvn.log" | sed -e "s#$d/##g" | scrub | sed -E 's/^.*(Fatal error compiling.*)$/\1/' | cut -c1-200 | head -3
}
qd "com.querydsl 5.1.0 + record @Embeddable, Boot 3.5" boot3 "" record compile
qd "com.querydsl 5.1.0 + record @Embeddable, Boot 4.2" boot4 "" record compile
qd "io.github.openfeign.querydsl 7.8 + record @Embeddable, Boot 4.2" boot4 openfeign record compile
qd "io.github.openfeign.querydsl 7.8, whole test suite, Boot 4.2" boot4 openfeign "" test
} > "$OUT/21-querydsl.txt"
echo "== 22 the native query parser switch"
{
for g in boot3 boot4; do
jar="$(jar_of $g spring-data-jpa)"
n=$(python3 -I scripts/jar_grep.py "$jar" 'spring.data.jpa.query.native.parser')
echo "$(basename "$jar"): class files containing the string spring.data.jpa.query.native.parser: $n"
done
echo "=== how 3.5 reads it (javap -c)"
javap -c -p -cp "$(jar_of boot3 spring-data-jpa)" 'org.springframework.data.jpa.repository.query.QueryEnhancerFactory$NativeQueryEnhancer' \
| grep -A1 'String spring.data.jpa.query.native.parser' | sed -E 's/^ +[0-9]+: //; s/#[0-9]+ +//'
} > "$OUT/22-native-parser-property.txt"
echo "done"