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:
@@ -0,0 +1,33 @@
|
||||
# Jakarta Data repositories on Hibernate, compared with Spring Data JPA
|
||||
|
||||
Runnable companion to the ankurm.com post on Jakarta Data with Hibernate (`@Find`, `@Query`, `@Select`) and how it compares
|
||||
with Spring Data JPA. Every transcript in [`output/`](output) is written by a test that asserts the same facts; the post quotes those files verbatim.
|
||||
|
||||
## Versions and status (checked against Maven Central on 2026-11-26)
|
||||
|
||||
| Profile | Hibernate ORM | Jakarta Data API | Status |
|
||||
|---|---|---|---|
|
||||
| `ga` (default) | 7.4.17.Final | 1.0.2 | GA |
|
||||
| `h8` (`-Ph8`) | 8.0.0.CR2 (24 Nov 2026) | 1.1.0-M4 | pre-release; Jakarta Data 1.1 is not final |
|
||||
| `spring-data` module | Spring Boot 4.2.0, Spring Data JPA 4.2.0, Hibernate 7.4.15.Final (Boot-managed) | n/a | GA |
|
||||
|
||||
JDK Temurin 25.0.5.1, H2 2.5.252, JUnit 6.1.3, Maven 3.9.11. `@Select`, `@Is` and `@First` exist only in Jakarta Data 1.1.0-M4.
|
||||
|
||||
## Run
|
||||
|
||||
./scripts/run-all.sh # regenerates all of output/ (needs JDK 25, Maven, network)
|
||||
cd hibernate-data && mvn test # GA line
|
||||
cd hibernate-data && mvn -Ph8 test # Hibernate 8 CR2 + Jakarta Data 1.1.0-M4
|
||||
./scripts/broken.sh ga|h8 # compile-time errors for the files in hibernate-data/src/broken
|
||||
cd spring-data && mvn test # the Spring Data JPA comparison
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `hibernate-data/src/main/java/com/ankurm/data/` | `Book`, `Library` (`@Find`/`@Query`), `StatefulLibrary` (EntityManager-backed) |
|
||||
| `hibernate-data/src/h8/java/` | `Catalog` (`@Select`, `@Is`, `@First`), compiled only with `-Ph8` |
|
||||
| `hibernate-data/src/test/` , `src/test-h8/` | `Lab` (boots Hibernate, records SQL), `Transcript`, the tests |
|
||||
| `hibernate-data/src/broken/` | repositories that must NOT compile; driven by `scripts/broken.sh` |
|
||||
| `spring-data/src/main/java/com/ankurm/sd/` | `BookRepository` and the two projection types |
|
||||
| `output/ga`, `output/h8`, `output/spring` | captured output; `output/00-version-check.txt` is the Maven Central check |
|
||||
@@ -0,0 +1,117 @@
|
||||
<?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>com.ankurm</groupId>
|
||||
<artifactId>jakarta-data-demo</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<artifactId>hibernate-data</artifactId>
|
||||
<name>Jakarta Data repositories on Hibernate (GA 7.4 and pre-release 8.0)</name>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- default: the GA line. Activate -Ph8 for Hibernate 8.0.0.CR2 + Jakarta Data 1.1.0-M4 (both pre-release). -->
|
||||
<hibernate.version>7.4.17.Final</hibernate.version>
|
||||
<jakarta.data.version>1.0.2</jakarta.data.version>
|
||||
<profile.name>ga</profile.name>
|
||||
<h2.version>2.5.252</h2.version>
|
||||
<junit.version>6.1.3</junit.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.data</groupId>
|
||||
<artifactId>jakarta.data-api</artifactId>
|
||||
<version>${jakarta.data.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>2.0.17</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.0</version>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-processor</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.4</version>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<profile.name>${profile.name}</profile.name>
|
||||
<hibernate.version>${hibernate.version}</hibernate.version>
|
||||
<jakarta.data.version>${jakarta.data.version}</jakarta.data.version>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>h8</id>
|
||||
<properties>
|
||||
<hibernate.version>8.0.0.CR2</hibernate.version>
|
||||
<jakarta.data.version>1.1.0-M4</jakarta.data.version>
|
||||
<profile.name>h8</profile.name>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-h8-sources</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals><goal>add-source</goal></goals>
|
||||
<configuration><sources><source>src/h8/java</source></sources></configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>add-h8-tests</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals><goal>add-test-source</goal></goals>
|
||||
<configuration><sources><source>src/test-h8/java</source></sources></configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.repository.Query;
|
||||
import jakarta.data.repository.Repository;
|
||||
import org.hibernate.StatelessSession;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/** "prise" is not an attribute of Book. */
|
||||
@Repository
|
||||
public interface BadHql {
|
||||
StatelessSession session();
|
||||
|
||||
@Query("where prise < :max")
|
||||
List<Book> cheaperThan(BigDecimal max);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.repository.Find;
|
||||
import jakarta.data.repository.OrderBy;
|
||||
import jakarta.data.repository.Repository;
|
||||
import org.hibernate.StatelessSession;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** "year" is not an attribute of Book (it is publishedYear). */
|
||||
@Repository
|
||||
public interface BadOrderBy {
|
||||
StatelessSession session();
|
||||
|
||||
@Find
|
||||
@OrderBy("year")
|
||||
List<Book> byAuthor(String author);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.repository.Find;
|
||||
import jakarta.data.repository.Repository;
|
||||
import org.hibernate.StatelessSession;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** The parameter is called "autor"; the entity attribute is "author". */
|
||||
@Repository
|
||||
public interface MisspelledParameter {
|
||||
StatelessSession session();
|
||||
|
||||
@Find
|
||||
List<Book> byAuthor(String autor);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.repository.Find;
|
||||
import jakarta.data.repository.Repository;
|
||||
import org.hibernate.StatelessSession;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** publishedYear is an int attribute; the parameter is a String. */
|
||||
@Repository
|
||||
public interface WrongParameterType {
|
||||
StatelessSession session();
|
||||
|
||||
@Find
|
||||
List<Book> byPublishedYear(String publishedYear);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.constraint.AtLeast;
|
||||
import jakarta.data.constraint.LessThan;
|
||||
import jakarta.data.repository.By;
|
||||
import jakarta.data.repository.Find;
|
||||
import jakarta.data.repository.First;
|
||||
import jakarta.data.repository.Is;
|
||||
import jakarta.data.repository.OrderBy;
|
||||
import jakarta.data.repository.Repository;
|
||||
import jakarta.data.repository.Select;
|
||||
import org.hibernate.StatelessSession;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Jakarta Data 1.1 features: @Select, @Is, @First. Only compiled with -Ph8 because jakarta.data-api 1.0.2
|
||||
* (the GA release) does not contain these annotations.
|
||||
*/
|
||||
@Repository
|
||||
public interface Catalog {
|
||||
|
||||
StatelessSession session();
|
||||
|
||||
/** @Select picks one attribute; the return type says what that attribute is. */
|
||||
@Find(Book.class)
|
||||
@Select("title")
|
||||
@OrderBy("title")
|
||||
List<String> titlesBy(String author);
|
||||
|
||||
/** A record return type with @Find: components are matched to entity attributes by name. */
|
||||
@Find(Book.class)
|
||||
@OrderBy("publishedYear")
|
||||
List<TitleAndYear> slimBooksBy(String author);
|
||||
|
||||
/** @Is turns a plain parameter into a comparison. */
|
||||
@Find
|
||||
@OrderBy("price")
|
||||
List<Book> pricedAtLeast(@By("price") @Is(AtLeast.class) BigDecimal min);
|
||||
|
||||
@Find
|
||||
@OrderBy("price")
|
||||
List<Book> youngerAndCheaper(@By("publishedYear") @Is(AtLeast.class) int since,
|
||||
@By("price") @Is(LessThan.class) BigDecimal below);
|
||||
|
||||
/** @First(n) is a limit without a PageRequest parameter. */
|
||||
@Find
|
||||
@OrderBy(value = "price", descending = true)
|
||||
@First(2)
|
||||
List<Book> twoMostExpensive(@By("publishedYear") @Is(AtLeast.class) int since);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
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,58 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.repository.Delete;
|
||||
import jakarta.data.repository.Find;
|
||||
import jakarta.data.repository.Insert;
|
||||
import jakarta.data.repository.OrderBy;
|
||||
import jakarta.data.repository.Query;
|
||||
import jakarta.data.repository.Repository;
|
||||
import jakarta.data.repository.Save;
|
||||
import org.hibernate.StatelessSession;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A Jakarta Data repository. This is only an interface: hibernate-processor writes the implementation
|
||||
* while javac runs (target/generated-sources/annotations/com/ankurm/data/_Library.java).
|
||||
*/
|
||||
@Repository
|
||||
public interface Library {
|
||||
|
||||
/** The "resource accessor": the generated class passes the StatelessSession it was constructed with. */
|
||||
StatelessSession session();
|
||||
|
||||
@Insert
|
||||
void add(Book book);
|
||||
|
||||
@Save
|
||||
void save(Book book);
|
||||
|
||||
@Delete
|
||||
void remove(Book book);
|
||||
|
||||
// ---- @Find: the parameter names ARE the query ----
|
||||
|
||||
@Find
|
||||
Optional<Book> byIsbn(String isbn);
|
||||
|
||||
@Find
|
||||
@OrderBy("publishedYear")
|
||||
List<Book> byAuthor(String author);
|
||||
|
||||
@Find
|
||||
List<Book> byAuthorAndPublishedYear(String author, int publishedYear);
|
||||
|
||||
// ---- @Query: HQL, parsed and type-checked at compile time ----
|
||||
|
||||
@Query("where price < :max order by price")
|
||||
List<Book> cheaperThan(BigDecimal max);
|
||||
|
||||
/** A projection through a record: positional match between select list and record components. */
|
||||
@Query("select title, publishedYear from Book where author = :author order by publishedYear")
|
||||
List<TitleAndYear> titlesBy(String author);
|
||||
|
||||
@Query("select count(*) from Book where author = :author")
|
||||
long countBy(String author);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.repository.Find;
|
||||
import jakarta.data.repository.Repository;
|
||||
import jakarta.persistence.EntityManager;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A repository backed by a stateful EntityManager instead of a StatelessSession. The accessor method's return type
|
||||
* decides which kind of repository hibernate-processor generates: StatelessSession gives a stateless one,
|
||||
* EntityManager gives one whose entities are managed and dirty-checked.
|
||||
*/
|
||||
@Repository
|
||||
public interface StatefulLibrary {
|
||||
EntityManager em();
|
||||
|
||||
@Find
|
||||
Optional<Book> byIsbn(String isbn);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
/** A projection: only two columns travel from the database. */
|
||||
public record TitleAndYear(String title, int publishedYear) {
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class CatalogTest {
|
||||
|
||||
@Test
|
||||
void selectIsAndFirst() {
|
||||
try (Lab lab = new Lab()) {
|
||||
Transcript t = new Transcript("04-select-is-first");
|
||||
lab.inTx(s -> {
|
||||
Catalog c = Lab.repo(Catalog.class, s);
|
||||
List<String> titles = c.titlesBy("Joshua Bloch");
|
||||
t.line("titlesBy(Bloch) @Select(title) -> " + titles);
|
||||
List<TitleAndYear> slim = c.slimBooksBy("Joshua Bloch");
|
||||
t.line("slimBooksBy(Bloch) record return -> " + slim);
|
||||
List<Book> atLeast = c.pricedAtLeast(new BigDecimal("48.00"));
|
||||
t.line("pricedAtLeast(48.00) @Is(AtLeast) -> " + atLeast.stream().map(b -> b.title + " " + b.price).toList());
|
||||
List<Book> yc = c.youngerAndCheaper(2018, new BigDecimal("50.00"));
|
||||
t.line("youngerAndCheaper(2018, 50.00) -> " + yc.stream().map(b -> b.title + " " + b.price).toList());
|
||||
List<Book> top = c.twoMostExpensive(2000);
|
||||
t.line("twoMostExpensive(2000) @First(2) -> " + top.stream().map(b -> b.title + " " + b.price).toList());
|
||||
assertEquals(List.of("Effective Java", "Java Puzzlers"), titles);
|
||||
assertEquals(2, slim.size());
|
||||
assertEquals(3, atLeast.size());
|
||||
assertEquals(2, yc.size());
|
||||
assertEquals(2, top.size());
|
||||
});
|
||||
t.line("SQL Hibernate prepared:").sql(Lab.SQL).write();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.StatelessSession;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.resource.jdbc.spi.StatementInspector;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Boots Hibernate on in-memory H2, seeds six books, and records every SQL statement it prepares. */
|
||||
public final class Lab implements AutoCloseable {
|
||||
|
||||
public static final List<String> SQL = new ArrayList<>();
|
||||
|
||||
/** Hibernate instantiates this by class name, so it must be public and static. */
|
||||
public static class Recorder implements StatementInspector {
|
||||
@Override
|
||||
public String inspect(String sql) {
|
||||
SQL.add(sql);
|
||||
return sql;
|
||||
}
|
||||
}
|
||||
|
||||
public final SessionFactory sf;
|
||||
|
||||
public Lab() {
|
||||
this(true);
|
||||
}
|
||||
|
||||
/** registerRepository=false leaves the repository interface out of the Configuration (see LibraryTest.queryNeedsRegistration). */
|
||||
public Lab(boolean registerRepository) {
|
||||
Configuration cfg = new Configuration()
|
||||
.addAnnotatedClass(Book.class)
|
||||
.setProperty("jakarta.persistence.jdbc.url", "jdbc:h2:mem:lib" + System.nanoTime() + ";DB_CLOSE_DELAY=-1")
|
||||
.setProperty("jakarta.persistence.jdbc.user", "sa")
|
||||
.setProperty("jakarta.persistence.jdbc.password", "")
|
||||
.setProperty("hibernate.hbm2ddl.auto", "create-drop")
|
||||
.setProperty("hibernate.session_factory.statement_inspector", Recorder.class.getName());
|
||||
if (registerRepository) {
|
||||
cfg.addAnnotatedClass(Library.class); // Hibernate 8: @Query methods are registered as named queries through the repository type
|
||||
}
|
||||
sf = cfg.buildSessionFactory();
|
||||
inTx(s -> {
|
||||
Library lib = repo(Library.class, s);
|
||||
lib.add(new Book("111", "Effective Java", "Joshua Bloch", 2001, "45.00"));
|
||||
lib.add(new Book("222", "Java Puzzlers", "Joshua Bloch", 2005, "39.50"));
|
||||
lib.add(new Book("333", "Java Concurrency in Practice", "Brian Goetz", 2006, "52.00"));
|
||||
lib.add(new Book("444", "Core Java", "Cay Horstmann", 2019, "60.00"));
|
||||
lib.add(new Book("555", "Java in a Nutshell", "Benjamin Evans", 2018, "30.00"));
|
||||
lib.add(new Book("666", "Modern Java in Action", "Raoul-Gabriel Urma", 2018, "48.00"));
|
||||
});
|
||||
SQL.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* The generated implementation is named Library_ on Hibernate 7.4 and _Library on Hibernate 8.0 (where Library_
|
||||
* became the Jakarta Persistence 4 static metamodel of the repository). Looking it up by name keeps one test source
|
||||
* for both profiles. Application code would use the CDI/Spring injection point or a single constructor call.
|
||||
*/
|
||||
public static <T> T repo(Class<T> iface, StatelessSession s) {
|
||||
for (String name : new String[]{iface.getName() + "_", iface.getPackageName() + "._" + iface.getSimpleName()}) {
|
||||
try {
|
||||
Class<?> c = Class.forName(name);
|
||||
if (iface.isAssignableFrom(c)) {
|
||||
return iface.cast(c.getConstructor(StatelessSession.class).newInstance(s));
|
||||
}
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
// try the next naming convention
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("no generated implementation for " + iface);
|
||||
}
|
||||
|
||||
/** Same lookup for a repository whose accessor is an EntityManager (a stateful repository). */
|
||||
public static <T, S> T repoFor(Class<T> iface, Class<S> sessionType, S session) {
|
||||
for (String name : new String[]{iface.getName() + "_", iface.getPackageName() + "._" + iface.getSimpleName()}) {
|
||||
try {
|
||||
Class<?> c = Class.forName(name);
|
||||
if (iface.isAssignableFrom(c)) {
|
||||
return iface.cast(c.getConstructor(sessionType).newInstance(session));
|
||||
}
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
// try the next naming convention
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("no generated implementation for " + iface);
|
||||
}
|
||||
|
||||
public static String implName(Class<?> iface) {
|
||||
for (String name : new String[]{iface.getName() + "_", iface.getPackageName() + "._" + iface.getSimpleName()}) {
|
||||
try {
|
||||
if (iface.isAssignableFrom(Class.forName(name))) {
|
||||
return name;
|
||||
}
|
||||
} catch (ClassNotFoundException ignored) {
|
||||
// try next
|
||||
}
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
|
||||
public void inTx(Consumer<StatelessSession> work) {
|
||||
sf.inStatelessTransaction(work);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
sf.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LibraryTest {
|
||||
|
||||
@Test
|
||||
void versions() {
|
||||
Transcript t = new Transcript("00-versions");
|
||||
t.line("profile " + System.getProperty("profile.name"));
|
||||
t.line("hibernate " + org.hibernate.Version.getVersionString());
|
||||
t.line("jakarta.data " + System.getProperty("jakarta.data.version"));
|
||||
t.line("java " + Runtime.version());
|
||||
t.line("implementation of Library is generated as " + Lab.implName(Library.class));
|
||||
t.write();
|
||||
assertNotNull(org.hibernate.Version.getVersionString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByIsbn() {
|
||||
try (Lab lab = new Lab()) {
|
||||
Transcript t = new Transcript("01-find-by-parameter-name");
|
||||
lab.inTx(s -> {
|
||||
Library lib = Lab.repo(Library.class, s);
|
||||
Optional<Book> b = lib.byIsbn("333");
|
||||
t.line("byIsbn(\"333\") -> " + b.orElseThrow());
|
||||
List<Book> bloch = lib.byAuthor("Joshua Bloch");
|
||||
t.line("byAuthor(\"Joshua Bloch\") @OrderBy -> " + bloch.stream().map(x -> x.title + "/" + x.publishedYear).toList());
|
||||
List<Book> one = lib.byAuthorAndPublishedYear("Joshua Bloch", 2005);
|
||||
t.line("byAuthorAndPublishedYear(Bloch,2005) -> " + one.stream().map(x -> x.title).toList());
|
||||
assertEquals("Java Concurrency in Practice", b.get().title);
|
||||
assertEquals(List.of("Effective Java", "Java Puzzlers"), bloch.stream().map(x -> x.title).toList());
|
||||
assertEquals(1, one.size());
|
||||
});
|
||||
t.line("SQL Hibernate prepared:").sql(Lab.SQL).write();
|
||||
assertEquals(3, Lab.SQL.size());
|
||||
assertTrue(Lab.SQL.get(1).contains("order by"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hqlQueryAndProjection() {
|
||||
try (Lab lab = new Lab()) {
|
||||
Transcript t = new Transcript("02-query-and-record-projection");
|
||||
lab.inTx(s -> {
|
||||
Library lib = Lab.repo(Library.class, s);
|
||||
List<Book> cheap = lib.cheaperThan(new BigDecimal("46.00"));
|
||||
t.line("cheaperThan(46.00) -> " + cheap.stream().map(x -> x.title + " " + x.price).toList());
|
||||
List<TitleAndYear> ty = lib.titlesBy("Joshua Bloch");
|
||||
t.line("titlesBy(Bloch) -> " + ty);
|
||||
long n = lib.countBy("Joshua Bloch");
|
||||
t.line("countBy(Bloch) -> " + n);
|
||||
assertEquals(3, cheap.size());
|
||||
assertEquals(new TitleAndYear("Effective Java", 2001), ty.get(0));
|
||||
assertEquals(2, n);
|
||||
});
|
||||
t.line("SQL Hibernate prepared:").sql(Lab.SQL).write();
|
||||
assertTrue(Lab.SQL.get(1).startsWith("select b1_0.title,b1_0.publishedYear") || Lab.SQL.get(1).contains("select b1_0.title"),
|
||||
"projection should select only title and year, was: " + Lab.SQL.get(1));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statelessMeansDetachedAndExplicit() {
|
||||
try (Lab lab = new Lab()) {
|
||||
Transcript t = new Transcript("03-stateless-no-dirty-checking");
|
||||
lab.inTx(s -> {
|
||||
Library lib = Lab.repo(Library.class, s);
|
||||
Book b = lib.byIsbn("111").orElseThrow();
|
||||
b.price = new BigDecimal("1.00"); // no persistence context: nothing watches this change
|
||||
t.line("changed price in memory to 1.00, no save() call");
|
||||
});
|
||||
lab.inTx(s -> {
|
||||
Library lib = Lab.repo(Library.class, s);
|
||||
BigDecimal after = lib.byIsbn("111").orElseThrow().price;
|
||||
t.line("price re-read from database: " + after);
|
||||
assertEquals(0, new BigDecimal("45.00").compareTo(after));
|
||||
Book b = lib.byIsbn("111").orElseThrow();
|
||||
b.price = new BigDecimal("1.00");
|
||||
lib.save(b); // @Save is an explicit upsert
|
||||
});
|
||||
lab.inTx(s -> {
|
||||
BigDecimal after = Lab.repo(Library.class, s).byIsbn("111").orElseThrow().price;
|
||||
t.line("after explicit save(): " + after);
|
||||
assertEquals(0, new BigDecimal("1.00").compareTo(after));
|
||||
});
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryNeedsRegistration() {
|
||||
try (Lab lab = new Lab(false)) {
|
||||
Transcript t = new Transcript("06-query-registration");
|
||||
String outcome;
|
||||
try {
|
||||
lab.inTx(s -> Lab.repo(Library.class, s).cheaperThan(new BigDecimal("46.00")));
|
||||
outcome = "worked without addAnnotatedClass(Library.class)";
|
||||
} catch (RuntimeException e) {
|
||||
outcome = e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||
}
|
||||
t.line("profile " + System.getProperty("profile.name") + ", repository NOT registered, calling cheaperThan(46.00):");
|
||||
t.line(outcome);
|
||||
t.write();
|
||||
if ("h8".equals(System.getProperty("profile.name"))) {
|
||||
assertTrue(outcome.contains("No query named"), outcome);
|
||||
} else {
|
||||
assertTrue(outcome.startsWith("worked"), outcome);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statefulRepositoryDirtyChecks() {
|
||||
try (Lab lab = new Lab()) {
|
||||
Transcript t = new Transcript("07-stateful-repository");
|
||||
t.line("implementation of StatefulLibrary is generated as " + Lab.implName(StatefulLibrary.class));
|
||||
Lab.SQL.clear();
|
||||
try (jakarta.persistence.EntityManager em = lab.sf.createEntityManager()) {
|
||||
em.getTransaction().begin();
|
||||
StatefulLibrary lib = Lab.repoFor(StatefulLibrary.class, jakarta.persistence.EntityManager.class, em);
|
||||
Book b = lib.byIsbn("111").orElseThrow();
|
||||
b.price = new BigDecimal("2.00"); // no save() call this time
|
||||
t.line("changed price to 2.00 in memory, no save() call, committing");
|
||||
em.getTransaction().commit();
|
||||
}
|
||||
try (jakarta.persistence.EntityManager em = lab.sf.createEntityManager()) {
|
||||
BigDecimal after = Lab.repoFor(StatefulLibrary.class, jakarta.persistence.EntityManager.class, em).byIsbn("111").orElseThrow().price;
|
||||
t.line("price re-read from database: " + after);
|
||||
assertEquals(0, new BigDecimal("2.00").compareTo(after));
|
||||
}
|
||||
t.line("SQL Hibernate prepared:").sql(Lab.SQL).write();
|
||||
assertTrue(Lab.SQL.stream().anyMatch(q -> q.startsWith("update Book")), "dirty checking should have issued an update");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
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", System.getProperty("profile.name", "ga"));
|
||||
Files.createDirectories(dir);
|
||||
Files.write(dir.resolve(name + ".txt"), lines, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
org/hibernate/orm/hibernate-core
|
||||
8.0.0.Beta3
|
||||
8.0.0.Beta4
|
||||
8.0.0.CR1
|
||||
8.0.0.CR2
|
||||
lastUpdated 20261124150926
|
||||
org/hibernate/orm/hibernate-processor
|
||||
8.0.0.Beta3
|
||||
8.0.0.Beta4
|
||||
8.0.0.CR1
|
||||
8.0.0.CR2
|
||||
lastUpdated 20261124150920
|
||||
jakarta/data/jakarta.data-api
|
||||
1.1.0-M1
|
||||
1.1.0-M2
|
||||
1.1.0-M3
|
||||
1.1.0-M4
|
||||
lastUpdated 20260827182903
|
||||
jakarta/persistence/jakarta.persistence-api
|
||||
4.0.0-M5
|
||||
4.0.0-M6
|
||||
4.0.0-M7
|
||||
4.0.0-M8
|
||||
lastUpdated 20261105172812
|
||||
org/springframework/data/spring-data-jpa
|
||||
4.2.0-M1
|
||||
4.2.0-M2
|
||||
4.2.0-RC1
|
||||
4.2.0
|
||||
lastUpdated 20261119150031
|
||||
org/springframework/boot/spring-boot-starter-parent
|
||||
4.2.0-M2
|
||||
4.2.0-RC1
|
||||
4.2.0-RC2
|
||||
4.2.0
|
||||
lastUpdated 20261119183517
|
||||
|
||||
newest Final (GA) hibernate-core:
|
||||
7.4.17.Final
|
||||
newest GA jakarta.data-api:
|
||||
1.0.2
|
||||
@@ -0,0 +1,5 @@
|
||||
profile ga
|
||||
hibernate 7.4.17.Final
|
||||
jakarta.data 1.0.2
|
||||
java 25.0.5.1+2-LTS
|
||||
implementation of Library is generated as com.ankurm.data.Library_
|
||||
@@ -0,0 +1,7 @@
|
||||
byIsbn("333") -> Book[333 'Java Concurrency in Practice' Brian Goetz 2006 52.00]
|
||||
byAuthor("Joshua Bloch") @OrderBy -> [Effective Java/2001, Java Puzzlers/2005]
|
||||
byAuthorAndPublishedYear(Bloch,2005) -> [Java Puzzlers]
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.isbn=?
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.author=? order by b1_0.publishedYear
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.author=? and b1_0.publishedYear=?
|
||||
@@ -0,0 +1,7 @@
|
||||
cheaperThan(46.00) -> [Java in a Nutshell 30.00, Java Puzzlers 39.50, Effective Java 45.00]
|
||||
titlesBy(Bloch) -> [TitleAndYear[title=Effective Java, publishedYear=2001], TitleAndYear[title=Java Puzzlers, publishedYear=2005]]
|
||||
countBy(Bloch) -> 2
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.price<? order by b1_0.price
|
||||
sql> select b1_0.title,b1_0.publishedYear from Book b1_0 where b1_0.author=? order by b1_0.publishedYear
|
||||
sql> select count(*) from Book b1_0 where b1_0.author=?
|
||||
@@ -0,0 +1,3 @@
|
||||
changed price in memory to 1.00, no save() call
|
||||
price re-read from database: 45.00
|
||||
after explicit save(): 1.00
|
||||
@@ -0,0 +1,8 @@
|
||||
##### BadHql
|
||||
com/ankurm/data/BadHql.java:[15,12] Could not interpret path expression 'prise'
|
||||
##### BadOrderBy
|
||||
com/ankurm/data/BadOrderBy.java:[16,5] no matching field named 'year' in entity class 'com.ankurm.data.Book'
|
||||
##### MisspelledParameter
|
||||
com/ankurm/data/MisspelledParameter.java:[15,32] no matching field named 'autor' in entity class 'com.ankurm.data.Book'
|
||||
##### WrongParameterType
|
||||
com/ankurm/data/WrongParameterType.java:[15,39] matching field has type 'java.lang.Integer' in entity class 'com.ankurm.data.Book'
|
||||
@@ -0,0 +1,2 @@
|
||||
profile ga, repository NOT registered, calling cheaperThan(46.00):
|
||||
worked without addAnnotatedClass(Library.class)
|
||||
@@ -0,0 +1,7 @@
|
||||
implementation of StatefulLibrary is generated as com.ankurm.data.StatefulLibrary_
|
||||
changed price to 2.00 in memory, no save() call, committing
|
||||
price re-read from database: 2.00
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.isbn=?
|
||||
sql> update Book set author=?,isbn=?,price=?,publishedYear=?,title=? where id=?
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.isbn=?
|
||||
@@ -0,0 +1,238 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.data.exceptions.DataException;
|
||||
import jakarta.data.exceptions.EmptyResultException;
|
||||
import jakarta.data.exceptions.EntityExistsException;
|
||||
import jakarta.data.exceptions.OptimisticLockingFailureException;
|
||||
import jakarta.persistence.NoResultException;
|
||||
import jakarta.persistence.NonUniqueResultException;
|
||||
import jakarta.persistence.PersistenceException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import java.util.Optional;
|
||||
import org.hibernate.StaleStateException;
|
||||
import org.hibernate.StatelessSession;
|
||||
import org.hibernate.exception.ConstraintViolationException;
|
||||
import static org.hibernate.query.Order.asc;
|
||||
import static org.hibernate.query.SortDirection.*;
|
||||
import org.hibernate.query.specification.SelectionSpecification;
|
||||
|
||||
/**
|
||||
* Implements Jakarta Data repository {@link com.ankurm.data.Library}
|
||||
**/
|
||||
public class Library_ implements Library {
|
||||
|
||||
|
||||
/**
|
||||
* @see #cheaperThan(BigDecimal)
|
||||
**/
|
||||
static final String CHEAPER_THAN_BigDecimal = "from Book where price < :max order by price";
|
||||
|
||||
/**
|
||||
* @see #titlesBy(String)
|
||||
**/
|
||||
static final String TITLES_BY_String = "select title, publishedYear from Book where author = :author order by publishedYear";
|
||||
|
||||
/**
|
||||
* @see #countBy(String)
|
||||
**/
|
||||
static final String COUNT_BY_String = "select count(*) from Book where author = :author";
|
||||
|
||||
|
||||
protected StatelessSession session;
|
||||
|
||||
public Library_(StatelessSession session) {
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StatelessSession session() {
|
||||
return session;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(Book book) {
|
||||
requireNonNull(book, "Null book");
|
||||
try {
|
||||
session.insert(book);
|
||||
}
|
||||
catch (ConstraintViolationException _ex) {
|
||||
throw new EntityExistsException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Book book) {
|
||||
requireNonNull(book, "Null book");
|
||||
try {
|
||||
if (session.getIdentifier(book) == null)
|
||||
session.insert(book);
|
||||
else
|
||||
session.upsert(book);
|
||||
}
|
||||
catch (StaleStateException _ex) {
|
||||
throw new OptimisticLockingFailureException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Book book) {
|
||||
requireNonNull(book, "Null book");
|
||||
try {
|
||||
session.delete(book);
|
||||
}
|
||||
catch (StaleStateException _ex) {
|
||||
throw new OptimisticLockingFailureException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#isbn isbn}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#byIsbn(String)
|
||||
**/
|
||||
@Override
|
||||
public Optional<Book> byIsbn(String isbn) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
isbn==null
|
||||
? _entity.get(Book_.isbn).isNull()
|
||||
: _builder.equal(_entity.get(Book_.isbn), isbn)
|
||||
);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select
|
||||
.uniqueResultOptional();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#author author}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#byAuthor(String)
|
||||
**/
|
||||
@Override
|
||||
public List<Book> byAuthor(String author) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
author==null
|
||||
? _entity.get(Book_.author).isNull()
|
||||
: _builder.equal(_entity.get(Book_.author), author)
|
||||
);
|
||||
var _spec = SelectionSpecification.create(_query);
|
||||
_spec.sort(asc(Book.class, "publishedYear"));
|
||||
try {
|
||||
var _select = _spec.createQuery(session);
|
||||
return _select
|
||||
.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#author author} and {@link Book#publishedYear publishedYear}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#byAuthorAndPublishedYear(String,int)
|
||||
**/
|
||||
@Override
|
||||
public List<Book> byAuthorAndPublishedYear(String author, int publishedYear) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
author==null
|
||||
? _entity.get(Book_.author).isNull()
|
||||
: _builder.equal(_entity.get(Book_.author), author),
|
||||
_builder.equal(_entity.get(Book_.publishedYear), publishedYear)
|
||||
);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select
|
||||
.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query {@value #CHEAPER_THAN_BigDecimal}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#cheaperThan(BigDecimal)
|
||||
**/
|
||||
@Override
|
||||
public List<Book> cheaperThan(BigDecimal max) {
|
||||
try {
|
||||
var _select = session.createSelectionQuery(CHEAPER_THAN_BigDecimal, Book.class)
|
||||
.setParameter("max", max);
|
||||
return _select
|
||||
.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query {@value #TITLES_BY_String}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#titlesBy(String)
|
||||
**/
|
||||
@Override
|
||||
public List<TitleAndYear> titlesBy(String author) {
|
||||
try {
|
||||
var _select = session.createSelectionQuery(TITLES_BY_String, TitleAndYear.class)
|
||||
.setParameter("author", author);
|
||||
return _select
|
||||
.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query {@value #COUNT_BY_String}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#countBy(String)
|
||||
**/
|
||||
@Override
|
||||
public long countBy(String author) {
|
||||
try {
|
||||
var _select = session.createSelectionQuery(COUNT_BY_String, long.class)
|
||||
.setParameter("author", author);
|
||||
return _select
|
||||
.getSingleResult();
|
||||
}
|
||||
catch (NoResultException _ex) {
|
||||
throw new EmptyResultException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (NonUniqueResultException _ex) {
|
||||
throw new jakarta.data.exceptions.NonUniqueResultException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
profile h8
|
||||
hibernate 8.0.0.CR2
|
||||
jakarta.data 1.1.0-M4
|
||||
java 25.0.5.1+2-LTS
|
||||
implementation of Library is generated as com.ankurm.data._Library
|
||||
@@ -0,0 +1,7 @@
|
||||
byIsbn("333") -> Book[333 'Java Concurrency in Practice' Brian Goetz 2006 52.00]
|
||||
byAuthor("Joshua Bloch") @OrderBy -> [Effective Java/2001, Java Puzzlers/2005]
|
||||
byAuthorAndPublishedYear(Bloch,2005) -> [Java Puzzlers]
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.isbn=?
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.author=? order by b1_0.publishedYear
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.author=? and b1_0.publishedYear=?
|
||||
@@ -0,0 +1,7 @@
|
||||
cheaperThan(46.00) -> [Java in a Nutshell 30.00, Java Puzzlers 39.50, Effective Java 45.00]
|
||||
titlesBy(Bloch) -> [TitleAndYear[title=Effective Java, publishedYear=2001], TitleAndYear[title=Java Puzzlers, publishedYear=2005]]
|
||||
countBy(Bloch) -> 2
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.price<? order by b1_0.price
|
||||
sql> select b1_0.title,b1_0.publishedYear from Book b1_0 where b1_0.author=? order by b1_0.publishedYear
|
||||
sql> select count(*) from Book b1_0 where b1_0.author=?
|
||||
@@ -0,0 +1,3 @@
|
||||
changed price in memory to 1.00, no save() call
|
||||
price re-read from database: 45.00
|
||||
after explicit save(): 1.00
|
||||
@@ -0,0 +1,11 @@
|
||||
titlesBy(Bloch) @Select(title) -> [Effective Java, Java Puzzlers]
|
||||
slimBooksBy(Bloch) record return -> [TitleAndYear[title=Effective Java, publishedYear=2001], TitleAndYear[title=Java Puzzlers, publishedYear=2005]]
|
||||
pricedAtLeast(48.00) @Is(AtLeast) -> [Modern Java in Action 48.00, Java Concurrency in Practice 52.00, Core Java 60.00]
|
||||
youngerAndCheaper(2018, 50.00) -> [Java in a Nutshell 30.00, Modern Java in Action 48.00]
|
||||
twoMostExpensive(2000) @First(2) -> [Core Java 60.00, Java Concurrency in Practice 52.00]
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.title from Book b1_0 where b1_0.author=? order by 1
|
||||
sql> select b1_0.title,b1_0.publishedYear from Book b1_0 where b1_0.author=? order by 2
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.price>=? order by b1_0.price
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.publishedYear>=? and b1_0.price<? order by b1_0.price
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.publishedYear>=? order by b1_0.price desc fetch first ? rows only
|
||||
@@ -0,0 +1,8 @@
|
||||
##### BadHql
|
||||
com/ankurm/data/BadHql.java:[15,12] Could not interpret path expression 'prise' [from Book where prise < :max]
|
||||
##### BadOrderBy
|
||||
com/ankurm/data/BadOrderBy.java:[16,5] no matching field named 'year' in entity class 'com.ankurm.data.Book'
|
||||
##### MisspelledParameter
|
||||
com/ankurm/data/MisspelledParameter.java:[15,32] no matching field named 'autor' in entity class 'com.ankurm.data.Book'
|
||||
##### WrongParameterType
|
||||
com/ankurm/data/WrongParameterType.java:[15,39] matching field has type 'java.lang.Integer' in entity class 'com.ankurm.data.Book'
|
||||
@@ -0,0 +1,2 @@
|
||||
profile h8, repository NOT registered, calling cheaperThan(46.00):
|
||||
DataException: No query named 'com.ankurm.data.Library#cheaperThan(java.math.BigDecimal)'
|
||||
@@ -0,0 +1,7 @@
|
||||
implementation of StatefulLibrary is generated as com.ankurm.data._StatefulLibrary
|
||||
changed price to 2.00 in memory, no save() call, committing
|
||||
price re-read from database: 2.00
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.isbn=?
|
||||
sql> update Book set author=?,isbn=?,price=?,publishedYear=?,title=? where id=?
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.publishedYear,b1_0.title from Book b1_0 where b1_0.isbn=?
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.persistence.TypedQueryReference;
|
||||
import jakarta.persistence.metamodel.StaticMetamodel;
|
||||
import jakarta.persistence.query.StaticTypedQueryReference;
|
||||
import java.math.BigDecimal;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.unmodifiableList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Static metamodel for {@link com.ankurm.data.Library}
|
||||
**/
|
||||
@StaticMetamodel(Library.class)
|
||||
@Generated("org.hibernate.processor.HibernateProcessor")
|
||||
public abstract class Library_ {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Return a reference to the query named {@code com.ankurm.data.Library#cheaperThan(java.math.BigDecimal)}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#cheaperThan(BigDecimal)
|
||||
**/
|
||||
public static TypedQueryReference<Book> cheaperThan(BigDecimal max) {
|
||||
return new StaticTypedQueryReference<>(
|
||||
"com.ankurm.data.Library#cheaperThan(java.math.BigDecimal)",
|
||||
Library.class,
|
||||
"cheaperThan",
|
||||
Book.class,
|
||||
List.of(BigDecimal.class),
|
||||
List.of("max"),
|
||||
unmodifiableList(asList((Object) max))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a reference to the query named {@code com.ankurm.data.Library#titlesBy(java.lang.String)}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#titlesBy(String)
|
||||
**/
|
||||
public static TypedQueryReference<TitleAndYear> titlesBy(String author) {
|
||||
return new StaticTypedQueryReference<>(
|
||||
"com.ankurm.data.Library#titlesBy(java.lang.String)",
|
||||
Library.class,
|
||||
"titlesBy",
|
||||
TitleAndYear.class,
|
||||
List.of(String.class),
|
||||
List.of("author"),
|
||||
unmodifiableList(asList((Object) author))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a reference to the query named {@code com.ankurm.data.Library#countBy(java.lang.String)}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#countBy(String)
|
||||
**/
|
||||
public static TypedQueryReference<Long> countBy(String author) {
|
||||
return new StaticTypedQueryReference<>(
|
||||
"com.ankurm.data.Library#countBy(java.lang.String)",
|
||||
Library.class,
|
||||
"countBy",
|
||||
Long.class,
|
||||
List.of(String.class),
|
||||
List.of("author"),
|
||||
unmodifiableList(asList((Object) author))
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import jakarta.data.exceptions.DataException;
|
||||
import jakarta.persistence.PersistenceException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import org.hibernate.StatelessSession;
|
||||
import static org.hibernate.query.restriction.JakartaDataRestriction.applySort;
|
||||
|
||||
/**
|
||||
* Implements Jakarta Data repository {@link com.ankurm.data.Catalog}
|
||||
**/
|
||||
@Generated("org.hibernate.processor.HibernateProcessor")
|
||||
public class _Catalog implements Catalog {
|
||||
|
||||
|
||||
|
||||
protected @Nonnull StatelessSession session;
|
||||
|
||||
public _Catalog(@Nonnull StatelessSession session) {
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nonnull StatelessSession session() {
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#author author}.
|
||||
*
|
||||
* @see com.ankurm.data.Catalog#titlesBy(String)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<String> titlesBy(String author) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(String.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.select(_entity.get(Book_.title));
|
||||
_query.where(
|
||||
author==null
|
||||
? _entity.get(Book_.author).isNull()
|
||||
: _builder.equal(_entity.get(Book_.author), author)
|
||||
);
|
||||
applySort(_Book.title.asc(), _query, _entity, _builder);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#author author}.
|
||||
*
|
||||
* @see com.ankurm.data.Catalog#slimBooksBy(String)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<TitleAndYear> slimBooksBy(String author) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(TitleAndYear.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.select(_builder.construct(TitleAndYear.class,
|
||||
_entity.get(Book_.title),
|
||||
_entity.get(Book_.publishedYear)));
|
||||
_query.where(
|
||||
author==null
|
||||
? _entity.get(Book_.author).isNull()
|
||||
: _builder.equal(_entity.get(Book_.author), author)
|
||||
);
|
||||
applySort(_Book.publishedYear.asc(), _query, _entity, _builder);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#price price}.
|
||||
*
|
||||
* @see com.ankurm.data.Catalog#pricedAtLeast(BigDecimal)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<Book> pricedAtLeast(BigDecimal price) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
price==null
|
||||
? _entity.get(Book_.price).isNull()
|
||||
: _builder.greaterThanOrEqualTo(_entity.get(Book_.price), price)
|
||||
);
|
||||
applySort(_Book.price.asc(), _query, _entity, _builder);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#publishedYear publishedYear} and {@link Book#price price}.
|
||||
*
|
||||
* @see com.ankurm.data.Catalog#youngerAndCheaper(int,BigDecimal)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<Book> youngerAndCheaper(int publishedYear, BigDecimal price) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
_builder.greaterThanOrEqualTo(_entity.get(Book_.publishedYear), publishedYear),
|
||||
price==null
|
||||
? _entity.get(Book_.price).isNull()
|
||||
: _builder.lessThan(_entity.get(Book_.price), price)
|
||||
);
|
||||
applySort(_Book.price.asc(), _query, _entity, _builder);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#publishedYear publishedYear}.
|
||||
*
|
||||
* @see com.ankurm.data.Catalog#twoMostExpensive(int)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<Book> twoMostExpensive(int publishedYear) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
_builder.greaterThanOrEqualTo(_entity.get(Book_.publishedYear), publishedYear)
|
||||
);
|
||||
applySort(_Book.price.desc(), _query, _entity, _builder);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.setMaxResults(2)
|
||||
.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package com.ankurm.data;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.annotation.Nonnull;
|
||||
import jakarta.data.exceptions.DataException;
|
||||
import jakarta.data.exceptions.EmptyResultException;
|
||||
import jakarta.data.exceptions.OptimisticLockingFailureException;
|
||||
import jakarta.persistence.EntityExistsException;
|
||||
import jakarta.persistence.NoResultException;
|
||||
import jakarta.persistence.NonUniqueResultException;
|
||||
import jakarta.persistence.OptimisticLockException;
|
||||
import jakarta.persistence.PersistenceException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import java.util.Optional;
|
||||
import org.hibernate.StatelessSession;
|
||||
import static org.hibernate.query.restriction.JakartaDataRestriction.applySort;
|
||||
|
||||
/**
|
||||
* Implements Jakarta Data repository {@link com.ankurm.data.Library}
|
||||
**/
|
||||
@Generated("org.hibernate.processor.HibernateProcessor")
|
||||
public class _Library implements Library {
|
||||
|
||||
|
||||
/**
|
||||
* @see #cheaperThan(BigDecimal)
|
||||
**/
|
||||
static final String CHEAPER_THAN_BigDecimal = "from Book where price < :max order by price";
|
||||
|
||||
/**
|
||||
* @see #titlesBy(String)
|
||||
**/
|
||||
static final String TITLES_BY_String = "select title, publishedYear from Book where author = :author order by publishedYear";
|
||||
|
||||
/**
|
||||
* @see #countBy(String)
|
||||
**/
|
||||
static final String COUNT_BY_String = "select count(*) from Book where author = :author";
|
||||
|
||||
|
||||
protected @Nonnull StatelessSession session;
|
||||
|
||||
public _Library(@Nonnull StatelessSession session) {
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nonnull StatelessSession session() {
|
||||
return session;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(@Nonnull Book book) {
|
||||
requireNonNull(book, "Null book");
|
||||
try {
|
||||
session.insert(book);
|
||||
}
|
||||
catch (EntityExistsException _ex) {
|
||||
throw new jakarta.data.exceptions.EntityExistsException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(@Nonnull Book book) {
|
||||
requireNonNull(book, "Null book");
|
||||
try {
|
||||
if (session.getIdentifier(book) == null)
|
||||
session.insert(book);
|
||||
else
|
||||
session.upsert(book);
|
||||
}
|
||||
catch (OptimisticLockException _ex) {
|
||||
throw new OptimisticLockingFailureException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(@Nonnull Book book) {
|
||||
requireNonNull(book, "Null book");
|
||||
try {
|
||||
session.delete(book);
|
||||
}
|
||||
catch (OptimisticLockException _ex) {
|
||||
throw new OptimisticLockingFailureException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#isbn isbn}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#byIsbn(String)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public Optional<Book> byIsbn(String isbn) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
isbn==null
|
||||
? _entity.get(Book_.isbn).isNull()
|
||||
: _builder.equal(_entity.get(Book_.isbn), isbn)
|
||||
);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.uniqueResultOptional();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#author author}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#byAuthor(String)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<Book> byAuthor(String author) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
author==null
|
||||
? _entity.get(Book_.author).isNull()
|
||||
: _builder.equal(_entity.get(Book_.author), author)
|
||||
);
|
||||
applySort(_Book.publishedYear.asc(), _query, _entity, _builder);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find {@link Book} by {@link Book#author author} and {@link Book#publishedYear publishedYear}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#byAuthorAndPublishedYear(String,int)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<Book> byAuthorAndPublishedYear(String author, int publishedYear) {
|
||||
var _builder = session.getCriteriaBuilder();
|
||||
var _query = _builder.createQuery(Book.class);
|
||||
var _entity = _query.from(Book.class);
|
||||
_query.where(
|
||||
author==null
|
||||
? _entity.get(Book_.author).isNull()
|
||||
: _builder.equal(_entity.get(Book_.author), author),
|
||||
_builder.equal(_entity.get(Book_.publishedYear), publishedYear)
|
||||
);
|
||||
try {
|
||||
var _select = session.createSelectionQuery(_query);
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query {@value #CHEAPER_THAN_BigDecimal}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#cheaperThan(BigDecimal)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<Book> cheaperThan(BigDecimal max) {
|
||||
try {
|
||||
var _select =
|
||||
session.createQuery(Library_.cheaperThan(max));
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query {@value #TITLES_BY_String}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#titlesBy(String)
|
||||
**/
|
||||
@Override
|
||||
@Nonnull
|
||||
public List<TitleAndYear> titlesBy(String author) {
|
||||
try {
|
||||
var _select =
|
||||
session.createQuery(Library_.titlesBy(author));
|
||||
return _select.getResultList();
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query {@value #COUNT_BY_String}.
|
||||
*
|
||||
* @see com.ankurm.data.Library#countBy(String)
|
||||
**/
|
||||
@Override
|
||||
public long countBy(String author) {
|
||||
try {
|
||||
var _select =
|
||||
session.createQuery(Library_.countBy(author));
|
||||
return _select.getSingleResult();
|
||||
}
|
||||
catch (NoResultException _ex) {
|
||||
throw new EmptyResultException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (NonUniqueResultException _ex) {
|
||||
throw new jakarta.data.exceptions.NonUniqueResultException(_ex.getMessage(), _ex);
|
||||
}
|
||||
catch (PersistenceException _ex) {
|
||||
throw new DataException(_ex.getMessage(), _ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
spring-data-jpa 4.2.0
|
||||
spring-framework 7.1.0
|
||||
hibernate 7.4.15.Final
|
||||
java 25.0.5.1+2-LTS
|
||||
@@ -0,0 +1,9 @@
|
||||
findByIsbn("333") -> Book[333 'Java Concurrency in Practice' Brian Goetz 2006 52.00]
|
||||
findByAuthorOrderByPublishedYear(Bloch) -> [Effective Java/2001, Java Puzzlers/2005]
|
||||
findByAuthorAndPublishedYear(Bloch,2005) -> [Java Puzzlers]
|
||||
findTop2ByPublishedYearGreaterThanEqualOrderByPriceDesc(2000) -> [Core Java 60.00, Java Concurrency in Practice 52.00]
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.isbn=?
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.author=? order by b1_0.published_year
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.author=? and b1_0.published_year=?
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.published_year>=? order by b1_0.price desc fetch first ? rows only
|
||||
@@ -0,0 +1,11 @@
|
||||
cheaperThan(46.00) -> [Java in a Nutshell 30.00, Java Puzzlers 39.50, Effective Java 45.00]
|
||||
findByAuthorOrderByPublishedYearAsc -> [TitleAndYear[title=Effective Java, publishedYear=2001], TitleAndYear[title=Java Puzzlers, publishedYear=2005]]
|
||||
findByAuthorOrderByTitle(TitleOnly) -> [Effective Java, Java Puzzlers]
|
||||
findByAuthorOrderByTitle(Book) -> [Effective Java, Java Puzzlers]
|
||||
countByAuthor(Bloch) -> 2
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.price<? order by b1_0.price
|
||||
sql> select b1_0.title,b1_0.published_year from book b1_0 where b1_0.author=? order by b1_0.published_year
|
||||
sql> select b1_0.title from book b1_0 where b1_0.author=? order by b1_0.title
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.author=? order by b1_0.title
|
||||
sql> select count(b1_0.id) from book b1_0 where b1_0.author=?
|
||||
@@ -0,0 +1,6 @@
|
||||
changed price to 1.00 in memory, no save() call, leaving the transaction
|
||||
price re-read from database: 1.00
|
||||
SQL Hibernate prepared:
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.isbn=?
|
||||
sql> update book set author=?,isbn=?,price=?,published_year=?,title=? where id=?
|
||||
sql> select b1_0.id,b1_0.author,b1_0.isbn,b1_0.price,b1_0.published_year,b1_0.title from book b1_0 where b1_0.isbn=?
|
||||
@@ -0,0 +1,2 @@
|
||||
BrokenDerivedConfig -> PropertyReferenceException: No property 'autor' found for type 'Book'; Did you mean 'author'
|
||||
BrokenQueryConfig -> PathElementException: Could not resolve attribute 'prise' of 'com.ankurm.sd.Book'
|
||||
@@ -0,0 +1,14 @@
|
||||
<?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>
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>jakarta-data-demo</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Jakarta Data with Hibernate vs Spring Data JPA</name>
|
||||
<modules>
|
||||
<module>hibernate-data</module>
|
||||
<module>spring-data</module>
|
||||
</modules>
|
||||
</project>
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Compiles each file in hibernate-data/src/broken/ on its own, inside a throwaway copy of the module, and records the
|
||||
# compiler's own message. Usage: scripts/broken.sh [ga|h8]. Needs JDK 25 and Maven. Writes hibernate-data/target/transcripts/<profile>/05-compile-errors.txt
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/../hibernate-data"
|
||||
P="${1:-ga}"
|
||||
PFLAG=""; [ "$P" = "h8" ] && PFLAG="-Ph8"
|
||||
OUT="target/transcripts/$P"; mkdir -p "$OUT"; : > "$OUT/05-compile-errors.txt"
|
||||
for f in src/broken/*.java; do
|
||||
name=$(basename "$f" .java)
|
||||
tmp=$(mktemp -d)
|
||||
cp -r pom.xml src "$tmp/"
|
||||
# the parent pom is needed only for coordinates; make the copy standalone
|
||||
sed -i '/<parent>/,/<\/parent>/d' "$tmp/pom.xml"
|
||||
sed -i 's#<artifactId>hibernate-data</artifactId>#<groupId>com.ankurm</groupId><version>1.0.0</version><artifactId>hibernate-data</artifactId>#' "$tmp/pom.xml"
|
||||
cp "$f" "$tmp/src/main/java/com/ankurm/data/"
|
||||
rm -rf "$tmp/src/broken" "$tmp/src/test" "$tmp/src/test-h8"
|
||||
[ -d "$tmp/src/h8" ] && [ "$P" != "h8" ] && rm -rf "$tmp/src/h8"
|
||||
echo "##### $name" >> "$OUT/05-compile-errors.txt"
|
||||
(cd "$tmp" && mvn -B -q $PFLAG compile 2>&1 | grep -E '^\[ERROR\] .*\.java:\[' | sed -E "s#$tmp/src/main/java/##; s#\[ERROR\] ##" | awk '!seen[$0]++') >> "$OUT/05-compile-errors.txt"
|
||||
rm -rf "$tmp"
|
||||
done
|
||||
cat "$OUT/05-compile-errors.txt"
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file in output/. Needs JDK 25 and Maven with network access (first run downloads dependencies).
|
||||
# output/ga Hibernate 7.4.17.Final + Jakarta Data 1.0.2 (both GA)
|
||||
# output/h8 Hibernate 8.0.0.CR2 + Jakarta Data 1.1.0-M4 (both pre-release)
|
||||
# output/spring Spring Boot 4.2.0 / Spring Data JPA 4.2.0 (GA)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
ROOT=$(pwd)
|
||||
rm -rf output && mkdir -p output/ga output/h8 output/spring
|
||||
bash scripts/verify-versions.sh > output/00-version-check.txt
|
||||
for P in ga h8; do
|
||||
FLAG=""; [ "$P" = h8 ] && FLAG="-Ph8"
|
||||
(cd hibernate-data && mvn -B -q $FLAG clean test >/dev/null)
|
||||
bash scripts/broken.sh "$P" >/dev/null
|
||||
cp hibernate-data/target/transcripts/$P/*.txt output/$P/
|
||||
for g in Library_ _Library Catalog_ _Catalog; do
|
||||
f=hibernate-data/target/generated-sources/annotations/com/ankurm/data/$g.java
|
||||
[ -f "$f" ] && cp "$f" "output/$P/generated-$g.java.txt"
|
||||
done
|
||||
done
|
||||
(cd spring-data && mvn -B -q clean test >/dev/null)
|
||||
cp spring-data/target/transcripts/*.txt output/spring/
|
||||
echo "wrote:"; find output -type f | sort
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prints, from Maven Central's maven-metadata.xml, the newest versions of every artifact this module depends on, so the
|
||||
# GA / pre-release status quoted in the article can be re-checked. Needs curl. Retries because Maven Central rate-limits.
|
||||
set -uo pipefail
|
||||
fetch() {
|
||||
local xml
|
||||
for i in 1 2 3 4 5 6; do
|
||||
xml=$(curl -sf "https://repo1.maven.org/maven2/$1/maven-metadata.xml") && { echo "$xml"; return 0; }
|
||||
sleep 8
|
||||
done
|
||||
return 1
|
||||
}
|
||||
show() {
|
||||
local xml
|
||||
xml=$(fetch "$1") || { echo "$1: could not fetch"; return 0; }
|
||||
echo "$1"
|
||||
echo "$xml" | grep -oE '<version>[^<]+' | sed 's/<version>//' | tail -4 | sed 's/^/ /'
|
||||
echo " lastUpdated $(echo "$xml" | grep -oE '<lastUpdated>[0-9]+' | sed 's/<lastUpdated>//')"
|
||||
}
|
||||
show org/hibernate/orm/hibernate-core
|
||||
show org/hibernate/orm/hibernate-processor
|
||||
show jakarta/data/jakarta.data-api
|
||||
show jakarta/persistence/jakarta.persistence-api
|
||||
show org/springframework/data/spring-data-jpa
|
||||
show org/springframework/boot/spring-boot-starter-parent
|
||||
echo
|
||||
echo "newest Final (GA) hibernate-core:"
|
||||
fetch org/hibernate/orm/hibernate-core | grep -oE '<version>[0-9.]+\.Final' | sed 's/<version>//' | tail -1 | sed 's/^/ /'
|
||||
echo "newest GA jakarta.data-api:"
|
||||
fetch jakarta/data/jakarta.data-api | grep -oE '<version>[0-9.]+<' | tr -d '<>version/' | tail -1 | sed 's/^/ /'
|
||||
exit 0
|
||||
@@ -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();
|
||||
}
|
||||
+11
@@ -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);
|
||||
}
|
||||
+14
@@ -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);
|
||||
}
|
||||
+15
@@ -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
|
||||
Reference in New Issue
Block a user