Add jakarta-data module: Jakarta Data repositories on Hibernate 7.4 / 8.0 CR2 vs Spring Data JPA 4.2

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4XrpfdpsacrvqnrBM
This commit is contained in:
Claude
2026-11-26 20:54:35 +05:30
parent 4f7ebd5cb0
commit 54c6d606ff
59 changed files with 2073 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
<?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 https://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>spring-data-compare</artifactId>
<version>1.0.0</version>
<name>The same repository in Spring Data JPA</name>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</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>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,40 @@
package com.ankurm.sd;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.math.BigDecimal;
/** The one entity both the Hibernate and the Spring Data modules use. */
@Entity
public class Book {
@Id
@GeneratedValue
public Long id;
@Column(unique = true, nullable = false)
public String isbn;
public String title;
public String author;
public int publishedYear;
public BigDecimal price;
public Book() {
}
public Book(String isbn, String title, String author, int publishedYear, String price) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.publishedYear = publishedYear;
this.price = new BigDecimal(price);
}
@Override
public String toString() {
return "Book[" + isbn + " '" + title + "' " + author + " " + publishedYear + " " + price + "]";
}
}
@@ -0,0 +1,36 @@
package com.ankurm.sd;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
/** The Spring Data JPA counterpart of the Library repository in the hibernate-data module. */
public interface BookRepository extends JpaRepository<Book, Long> {
// ---- derived queries: the METHOD NAME is the query, parsed when the application context starts ----
Optional<Book> findByIsbn(String isbn);
List<Book> findByAuthorOrderByPublishedYear(String author);
List<Book> findByAuthorAndPublishedYear(String author, int publishedYear);
long countByAuthor(String author);
List<Book> findTop2ByPublishedYearGreaterThanEqualOrderByPriceDesc(int since);
// ---- @Query: JPQL kept in a string, validated when the application context starts ----
@Query("select b from Book b where b.price < :max order by b.price")
List<Book> cheaperThan(@Param("max") BigDecimal max);
// ---- projections: the RETURN TYPE decides which columns are selected ----
List<TitleAndYear> findByAuthorOrderByPublishedYearAsc(String author);
<T> List<T> findByAuthorOrderByTitle(String author, Class<T> type);
}
@@ -0,0 +1,7 @@
package com.ankurm.sd;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
}
@@ -0,0 +1,5 @@
package com.ankurm.sd;
/** A class-based (DTO) projection: Spring Data matches record components to entity properties by name. */
public record TitleAndYear(String title, int publishedYear) {
}
@@ -0,0 +1,6 @@
package com.ankurm.sd;
/** An interface-based projection: Spring Data returns a proxy exposing only getTitle(). */
public interface TitleOnly {
String getTitle();
}
@@ -0,0 +1,11 @@
package com.ankurm.broken.derived;
import com.ankurm.sd.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/** Lives outside com.ankurm.sd on purpose, so the normal application never sees it. "autor" is a typo of "author". */
public interface BrokenRepository extends JpaRepository<Book, Long> {
List<Book> findByAutor(String autor);
}
@@ -0,0 +1,14 @@
package com.ankurm.broken.query;
import com.ankurm.sd.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.math.BigDecimal;
import java.util.List;
/** "prise" is not an attribute of Book. */
public interface BrokenQueryRepository extends JpaRepository<Book, Long> {
@Query("select b from Book b where b.prise < :max")
List<Book> cheaperThan(BigDecimal max);
}
@@ -0,0 +1,15 @@
package com.ankurm.brokenconfig;
import com.ankurm.sd.Book;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.persistence.autoconfigure.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/** Boots a context whose only repository is the deliberately broken one in com.ankurm.broken.derived. */
@Configuration
@EnableAutoConfiguration
@EntityScan(basePackageClasses = Book.class)
@EnableJpaRepositories(basePackages = "com.ankurm.broken.derived")
public class BrokenDerivedConfig {
}
@@ -0,0 +1,15 @@
package com.ankurm.brokenconfig;
import com.ankurm.sd.Book;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.persistence.autoconfigure.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/** Boots a context whose only repository is the deliberately broken one in com.ankurm.broken.query. */
@Configuration
@EnableAutoConfiguration
@EntityScan(basePackageClasses = Book.class)
@EnableJpaRepositories(basePackages = "com.ankurm.broken.query")
public class BrokenQueryConfig {
}
@@ -0,0 +1,124 @@
package com.ankurm.sd;
import org.hibernate.Version;
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.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.SpringVersion;
import org.springframework.transaction.support.TransactionTemplate;
import java.math.BigDecimal;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class BookRepositoryTest {
@Autowired
BookRepository repo;
@Autowired
TransactionTemplate tx;
@BeforeEach
void seed() {
repo.deleteAll();
repo.saveAll(List.of(
new Book("111", "Effective Java", "Joshua Bloch", 2001, "45.00"),
new Book("222", "Java Puzzlers", "Joshua Bloch", 2005, "39.50"),
new Book("333", "Java Concurrency in Practice", "Brian Goetz", 2006, "52.00"),
new Book("444", "Core Java", "Cay Horstmann", 2019, "60.00"),
new Book("555", "Java in a Nutshell", "Benjamin Evans", 2018, "30.00"),
new Book("666", "Modern Java in Action", "Raoul-Gabriel Urma", 2018, "48.00")));
SqlRecorder.SQL.clear();
}
@Test
void versions() {
Transcript t = new Transcript("00-versions");
t.line("spring-data-jpa " + org.springframework.data.jpa.repository.JpaRepository.class.getPackage().getImplementationVersion());
t.line("spring-framework " + SpringVersion.getVersion());
t.line("hibernate " + Version.getVersionString());
t.line("java " + Runtime.version());
t.write();
}
@Test
void derivedQueries() {
Transcript t = new Transcript("01-derived-queries");
var b = repo.findByIsbn("333").orElseThrow();
t.line("findByIsbn(\"333\") -> " + b);
var bloch = repo.findByAuthorOrderByPublishedYear("Joshua Bloch");
t.line("findByAuthorOrderByPublishedYear(Bloch) -> " + bloch.stream().map(x -> x.title + "/" + x.publishedYear).toList());
var one = repo.findByAuthorAndPublishedYear("Joshua Bloch", 2005);
t.line("findByAuthorAndPublishedYear(Bloch,2005) -> " + one.stream().map(x -> x.title).toList());
var top = repo.findTop2ByPublishedYearGreaterThanEqualOrderByPriceDesc(2000);
t.line("findTop2ByPublishedYearGreaterThanEqualOrderByPriceDesc(2000) -> " + top.stream().map(x -> x.title + " " + x.price).toList());
t.line("SQL Hibernate prepared:").sql(SqlRecorder.SQL).write();
assertEquals("Java Concurrency in Practice", b.title);
assertEquals(2, bloch.size());
assertEquals(1, one.size());
assertEquals(2, top.size());
}
@Test
void queryAndProjections() {
Transcript t = new Transcript("02-query-and-projections");
var cheap = repo.cheaperThan(new BigDecimal("46.00"));
t.line("cheaperThan(46.00) -> " + cheap.stream().map(x -> x.title + " " + x.price).toList());
var dto = repo.findByAuthorOrderByPublishedYearAsc("Joshua Bloch");
t.line("findByAuthorOrderByPublishedYearAsc -> " + dto);
var titles = repo.findByAuthorOrderByTitle("Joshua Bloch", TitleOnly.class);
t.line("findByAuthorOrderByTitle(TitleOnly) -> " + titles.stream().map(TitleOnly::getTitle).toList());
var full = repo.findByAuthorOrderByTitle("Joshua Bloch", Book.class);
t.line("findByAuthorOrderByTitle(Book) -> " + full.stream().map(x -> x.title).toList());
long n = repo.countByAuthor("Joshua Bloch");
t.line("countByAuthor(Bloch) -> " + n);
t.line("SQL Hibernate prepared:").sql(SqlRecorder.SQL).write();
assertEquals(3, cheap.size());
assertEquals(new TitleAndYear("Effective Java", 2001), dto.get(0));
assertEquals(2, n);
assertTrue(SqlRecorder.SQL.get(1).startsWith("select b1_0.title,b1_0.published_year") || SqlRecorder.SQL.get(1).startsWith("select b1_0.title,b1_0.publishedYear"),
"DTO projection should select two columns: " + SqlRecorder.SQL.get(1));
}
@Test
void managedEntitiesDirtyCheck() {
Transcript t = new Transcript("03-managed-entities-dirty-check");
SqlRecorder.SQL.clear();
tx.executeWithoutResult(s -> {
Book b = repo.findByIsbn("111").orElseThrow();
b.price = new BigDecimal("1.00"); // no save() call: the persistence context notices
t.line("changed price to 1.00 in memory, no save() call, leaving the transaction");
});
BigDecimal after = repo.findByIsbn("111").orElseThrow().price;
t.line("price re-read from database: " + after);
t.line("SQL Hibernate prepared:").sql(SqlRecorder.SQL).write();
assertEquals(0, new BigDecimal("1.00").compareTo(after));
assertTrue(SqlRecorder.SQL.stream().anyMatch(q -> q.startsWith("update")));
}
@Test
void mistakesSurfaceAtStartupNotAtCompileTime() {
Transcript t = new Transcript("04-startup-failures");
for (Class<?> cfg : new Class<?>[]{com.ankurm.brokenconfig.BrokenDerivedConfig.class, com.ankurm.brokenconfig.BrokenQueryConfig.class}) {
String root;
try (ConfigurableApplicationContext ctx = new SpringApplication(cfg).run("--spring.main.web-application-type=none",
"--spring.datasource.url=jdbc:h2:mem:broken" + cfg.getSimpleName() + ";DB_CLOSE_DELAY=-1", "--logging.level.root=OFF")) {
root = "application context started: the mistake was NOT caught";
} catch (Throwable e) {
Throwable r = e;
while (r.getCause() != null) {
r = r.getCause();
}
root = r.getClass().getSimpleName() + ": " + r.getMessage().lines().findFirst().orElse("");
}
t.line(cfg.getSimpleName() + " -> " + root);
assertFalse(root.startsWith("application context started"), root);
}
t.write();
}
}
@@ -0,0 +1,17 @@
package com.ankurm.sd;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** Records every SQL statement Hibernate prepares. Hibernate instantiates it by class name. */
public class SqlRecorder implements StatementInspector {
public static final List<String> SQL = new CopyOnWriteArrayList<>();
@Override
public String inspect(String sql) {
SQL.add(sql);
return sql;
}
}
@@ -0,0 +1,41 @@
package com.ankurm.sd;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Collects lines and writes them to target/transcripts/<profile>/NN-name.txt. The tests assert the same facts. */
public final class Transcript {
private final List<String> lines = new ArrayList<>();
private final String name;
public Transcript(String name) {
this.name = name;
}
public Transcript line(String s) {
lines.add(s);
return this;
}
public Transcript sql(List<String> sql) {
for (String s : sql) {
lines.add("sql> " + s.replaceAll("\\s+", " ").trim());
}
return this;
}
public void write() {
try {
Path dir = Path.of("target", "transcripts");
Files.createDirectories(dir);
Files.write(dir.resolve(name + ".txt"), lines, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,5 @@
spring.datasource.url=jdbc:h2:mem:lib;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.sd.SqlRecorder
logging.level.root=WARN