Hibernate Orphan Removal: orphanRemoval = true Explained
orphanRemoval = true deletes a child entity as soon as it leaves its parent’s association. See the SQL Hibernate 7 runs, how it differs from CascadeType.REMOVE, and the common mistakes.
orphanRemoval = true deletes a child entity as soon as it leaves its parent’s association. See the SQL Hibernate 7 runs, how it differs from CascadeType.REMOVE, and the common mistakes.
Test code that looks up a JNDI DataSource without an application server: register a small in-memory JNDI provider or Simple-JNDI, bind an H2 DataSource under the production name, bootstrap Hibernate 7 with it and run CRUD in JUnit 6. Or skip JNDI and pass the DataSource object.
Hibernate sends inserts, updates and deletes in JDBC batches once hibernate.jdbc.batch_size is set. Measured on Hibernate 7.4: why IDENTITY ids stop batching, how flush() and clear() keep memory flat, and when to use order_inserts, StatelessSession or a JPQL bulk statement.
Call a stored procedure from Hibernate with StoredProcedureQuery: IN and OUT parameters, result sets mapped to entities, named procedures and Spring Data @Procedure.
Hibernate aggregate functions compute one value from many rows. Learn count, min, max, sum and avg in HQL, JPQL and the Criteria API, their Java return types, group by, having, null handling and Hibernate’s listagg, filter and window functions.
Hibernate Search adds full-text search to Hibernate entities. Map fields with @FullTextField, @KeywordField and @GenericField, let the index follow every commit, rebuild it with the MassIndexer, and search with match, phrase, bool, range, sorting, paging and highlighting on Hibernate Search 8.4 and Lucene.
A Hibernate interceptor gets a callback when an entity is persisted, changed, removed or loaded, with the old and new property values. Build an audit trail with onPersist, onFlushDirty and onRemove in Hibernate 7, pick the right scope, and rewrite SQL with a StatementInspector.
Hibernate pagination loads a query result one page at a time with setFirstResult() and setMaxResults(). See the SQL for offset and keyset pages, page counts, the ORDER BY trap, join fetch paging and ScrollableResults on Hibernate 7.4.
Sort Hibernate query results with JPQL order by, Criteria orderBy and Hibernate 7 SelectionSpecification, and sort collections with @OrderBy, @OrderColumn, @SortNatural and @SortComparator.
Delete an entity in Hibernate 7 with em.remove() after find() or getReference(), fix the detached entity error, and use a JPQL bulk delete without leaving stale objects or hitting foreign key errors.
The seven JPA lifecycle callbacks in Hibernate 7.4, when each one runs relative to persist(), flush and commit, entity listeners and default listeners in orm.xml, what a callback must not do, and Hibernate’s own event listeners.
Create one EntityManagerFactory per database in Hibernate 7.4, from persistence.xml, from Java code with PersistenceConfiguration or HibernatePersistenceConfiguration, or from a PersistenceUnitInfo, then open one EntityManager per unit of work with runInTransaction() and callInTransaction().
HikariCP is a lightweight JDBC connection pool. Learn about various options for configuring the HikariCP with Spring boot JPA and hibernate.
Build a contacts address book with Spring MVC, Hibernate 7 and Thymeleaf on Spring Boot 4: list, create, edit and delete pages, form validation, Post/Redirect/Get, and MockMvc and @DataJpaTest tests.
Hibernate.initialize() loads a lazy proxy or a lazy collection while the EntityManager is open, so the data is usable after the transaction ends. Examples with the SQL, unproxy(), size(), the closed-session error and the N+1 alternatives.
@NamedStoredProcedureQuery declares a stored procedure call once on an entity and runs it by name. Learn every attribute, parameter modes, result mapping to entities and records, hints and the errors you meet.
Hibernate reads mapping metadata from annotations or from XML files. We map one Bicycle entity with annotations, orm.xml and the deprecated hbm.xml, and override annotations with orm.xml in Hibernate 7.4.
Hibernate lazy loading reads an association only when the code first uses it. See the SQL that LAZY and EAGER run, how proxies and PersistentBag work, and how to fix LazyInitializationException with join fetch, entity graphs, Hibernate.initialize() or a DTO projection.
A JPA cascade type repeats persist, merge, remove, refresh or detach from a parent entity to its children. See what each CascadeType does in Hibernate 7, the SQL it runs, what goes wrong without it, and which one to pick.
merge() copies a detached object onto a managed instance and returns that copy, while refresh() reloads a managed entity from its row and discards unsaved changes. See the SQL, the OptimisticLockException of an outdated merge, and what replaced Session.update() in Hibernate 7.
Hibernate get() loads an entity at once and returns null for a missing row; load() returns a proxy and fails on first use. In Hibernate 7, load() is removed and get() is deprecated, so we use find() and getReference().
Hibernate returns one object per row inside a session but a new object in every other session. Implement equals() and hashCode() for entities with a generated id, a business key or a UUID, make them proxy-safe, and avoid Lombok @Data.
Configure c3p0 as Hibernate 7’s connection pool with hibernate.c3p0 settings, check it in the logs and with pool statistics, size it, close and test idle connections, find leaks, and use c3p0 as the DataSource in Spring Boot 4.
Unit test Hibernate repositories against an in-memory H2 database with JUnit 6: one EntityManagerFactory per test class, data from import.sql, a fresh copy of the data before every test with truncate(), and the H2 settings and pitfalls that break tests.
Build a Hibernate SessionFactory in Hibernate 7.4 with HibernatePersistenceConfiguration, the native StandardServiceRegistryBuilder and MetadataSources API, the Configuration class, hibernate.cfg.xml, or unwrap() from an EntityManagerFactory. Then share one factory across threads and close it at shutdown.
Map BLOB and CLOB columns in Hibernate 7 with @Lob on byte[], String, Blob and Clob fields. See the generated column types on H2, MySQL and PostgreSQL, how to stream large files with Blob, and why @Basic(fetch = LAZY) needs bytecode enhancement.
EntityManager find() loads an entity with a SELECT or returns null, while getReference() returns a proxy without SQL. See when each runs SQL, when EntityNotFoundException and LazyInitializationException are thrown, and how to set a foreign key without loading the entity.
Map a natural id such as a license plate with Hibernate’s @NaturalId, load entities with em.find(…, KeyType.NATURAL), handle mutable and composite natural ids, and cache lookups with @NaturalIdCache, with the SQL and statement counts from Hibernate 7.4.
A Hibernate named query is a JPQL or SQL query declared once and run by name. Learn @NamedQuery, @NamedNativeQuery, orm.xml, parameters, result types, the startup check and JPA 3.2 typed references.
The Hibernate second level cache shares entity data across all sessions of an EntityManagerFactory. Learn the lookup order, what the cache stores, the concurrency strategies, collection and query caching, statistics and eviction with Hibernate 7.4 and Ehcache 3.
The Hibernate first level cache is the persistence context of one EntityManager. See with counted SQL on Hibernate 7.4 when find() and queries hit the database, how detach(), evict(), clear() and refresh() work, and how to keep long transactions small.
To insert an object with Hibernate, we pass a new entity to persist() inside a transaction. Learn when the INSERT runs for IDENTITY, SEQUENCE and assigned ids, how merge() and HQL insert statements work, and what replaced Session.save() in Hibernate 7.
Build your first Hibernate application with Hibernate 7.4, Java 25 and H2: the Maven dependencies, an entity, the configuration, and save, read, update and delete with the SQL each call runs.
HowToDoInJava provides tutorials and how-to guides on Java and related technologies.
It also shares the best practices, algorithms & solutions and frequently asked interview questions.