Add hibernate-demo: get() vs load(), merge() vs refresh(), inserting objects (Hibernate 7.4.1.Final + Spring Boot 4.1.0)
Adds a JUnit test suite (GetVsGetReferenceTest, MergeRefreshTest, OptimisticLockTest, IdentityBatchTest, SequenceBatchTest, AllocationSizeSweepTest, BatchSizeSweepTest) so every surprising behavior described in the three companion posts has a reproducible test, alongside the original CommandLineRunner scenarios. Rewrites all three doc chapters and the README around the new experiments: the get()/getReference() same-session matrix, the merge()/refresh() experiments (including exactly when OptimisticLockException surfaces and a corrected LAZY-plus- cascade merge() result), and two new sweeps (allocationSize, batch_size) for batch inserts.
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package com.ankurm.hibernatedemo;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.hibernatedemo.model.WidgetSequence;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.stat.Statistics;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/**
|
||||
* Backs ankurm.com post 4861. Docs: docs/03-inserting-objects.md.
|
||||
* Run with {@code ./mvnw -Dtest=SequenceBatchTest test}.
|
||||
*
|
||||
* <p>{@link WidgetSequence} sets {@code allocationSize = 25}, matching
|
||||
* {@code hibernate.jdbc.batch_size} in application.yml. See {@code AllocationSizeSweepTest} for
|
||||
* what happens when the two are deliberately mismatched.
|
||||
*/
|
||||
@SpringBootTest
|
||||
class SequenceBatchTest {
|
||||
|
||||
private static final int ROW_COUNT = 30;
|
||||
|
||||
@Autowired
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@Test
|
||||
void sequenceGeneratorAllowsBatching_fourPreparedStatementsForThirtyRows() {
|
||||
SessionFactory sessionFactory = emf.unwrap(SessionFactory.class);
|
||||
Statistics stats = sessionFactory.getStatistics();
|
||||
stats.clear();
|
||||
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
for (int i = 1; i <= ROW_COUNT; i++) {
|
||||
em.persist(new WidgetSequence("sequence-" + i));
|
||||
}
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
|
||||
assertThat(stats.getEntityInsertCount()).isEqualTo(ROW_COUNT);
|
||||
assertThat(stats.getPrepareStatementCount())
|
||||
.as("30 rows at batch_size=25 is 2 insert batches (25 + 5); allocationSize=25 "
|
||||
+ "means the first 25 ids come from one sequence call and the remaining "
|
||||
+ "5 force a second -- 2 insert batches + 2 sequence calls = 4")
|
||||
.isEqualTo(4);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user