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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user