package com.ankurm.hibernatedemo.scenario; import com.ankurm.hibernatedemo.model.WidgetIdentity; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.hibernate.stat.Statistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; /** * Backs ankurm.com post 4861 ("inserting objects efficiently") and * docs/03-inserting-objects.md. Captured verbatim into docs/output/insert-identity.txt by * {@code scripts/run.sh insert-identity}. * *

Same {@code hibernate.jdbc.batch_size} and {@code hibernate.order_inserts} settings as * {@link InsertSequenceRunner} -- the only difference is {@link WidgetIdentity}'s * {@code GenerationType.IDENTITY} strategy. Compare the two captured output files directly; * the diff between them is the entire point of this pair. */ @Component @Profile("insert-identity") public class InsertIdentityRunner implements CommandLineRunner { private static final Logger DEMO = LoggerFactory.getLogger("DEMO"); private static final int ROW_COUNT = 30; private final EntityManagerFactory emf; public InsertIdentityRunner(EntityManagerFactory emf) { this.emf = emf; } @Override public void run(String... args) { SessionFactory sessionFactory = emf.unwrap(SessionFactory.class); Statistics stats = sessionFactory.getStatistics(); stats.clear(); DEMO.info("--- inserting {} WidgetIdentity rows (GenerationType.IDENTITY) ---", ROW_COUNT); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); for (int i = 1; i <= ROW_COUNT; i++) { em.persist(new WidgetIdentity("identity-" + i)); } em.getTransaction().commit(); em.close(); DEMO.info("entityInsertCount = {}", stats.getEntityInsertCount()); DEMO.info("prepareStatementCount = {}", stats.getPrepareStatementCount()); DEMO.info("(with IDENTITY, expect prepareStatementCount to land close to entityInsertCount --" + " each insert has to go to the database immediately to hand back the generated key," + " so there is nothing left for hibernate.jdbc.batch_size to batch)"); } }