Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6R1spapM7nBteaqeo
90 lines
2.3 KiB
Java
90 lines
2.3 KiB
Java
package com.ankurm.nplusone;
|
|
|
|
import java.util.UUID;
|
|
import java.util.function.Consumer;
|
|
import java.util.function.Function;
|
|
import org.h2.jdbcx.JdbcDataSource;
|
|
import org.hibernate.Session;
|
|
import org.hibernate.SessionFactory;
|
|
import org.hibernate.boot.MetadataSources;
|
|
import org.hibernate.boot.registry.StandardServiceRegistry;
|
|
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
|
|
|
/**
|
|
* Plain Hibernate bootstrap on an in-memory H2, with the DataSource wrapped by {@link QueryGuard}
|
|
* and Hibernate's own statistics switched on, so both counters can be compared on the same code.
|
|
*/
|
|
public final class Db implements AutoCloseable {
|
|
|
|
private final SessionFactory sf;
|
|
|
|
private Db(SessionFactory sf) {
|
|
this.sf = sf;
|
|
}
|
|
|
|
public static Db open() {
|
|
JdbcDataSource h2 = new JdbcDataSource();
|
|
h2.setURL("jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1");
|
|
h2.setUser("sa");
|
|
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
|
|
.applySetting("jakarta.persistence.nonJtaDataSource", QueryGuard.wrap(h2))
|
|
.applySetting("hibernate.hbm2ddl.auto", "create-drop")
|
|
.applySetting("hibernate.generate_statistics", "true")
|
|
.build();
|
|
MetadataSources sources = new MetadataSources(registry)
|
|
.addAnnotatedClass(Author.class)
|
|
.addAnnotatedClass(Book.class);
|
|
return new Db(sources.buildMetadata().buildSessionFactory());
|
|
}
|
|
|
|
public SessionFactory sf() {
|
|
return sf;
|
|
}
|
|
|
|
/** Inserts {@code authors} authors with {@code booksEach} books each, then clears every counter. */
|
|
public void seed(int authors, int booksEach) {
|
|
txv(s -> {
|
|
for (int a = 0; a < authors; a++) {
|
|
Author author = new Author("author-" + a);
|
|
for (int b = 0; b < booksEach; b++) {
|
|
author.addBook(new Book("book-" + a + "-" + b));
|
|
}
|
|
s.persist(author);
|
|
}
|
|
});
|
|
sf.getStatistics().clear();
|
|
QueryGuard.reset();
|
|
}
|
|
|
|
public <T> T tx(Function<Session, T> work) {
|
|
try (Session s = sf.openSession()) {
|
|
var t = s.beginTransaction();
|
|
try {
|
|
T r = work.apply(s);
|
|
t.commit();
|
|
return r;
|
|
}
|
|
catch (RuntimeException e) {
|
|
if (t.isActive()) {
|
|
t.rollback();
|
|
}
|
|
throw e;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void txv(Consumer<Session> work) {
|
|
tx(s -> {
|
|
work.accept(s);
|
|
return null;
|
|
});
|
|
}
|
|
|
|
@Override
|
|
public void close() {
|
|
if (sf.isOpen()) {
|
|
sf.close();
|
|
}
|
|
}
|
|
}
|