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.
Hibernate ORM enables developers to more easily write applications whose data outlives the application process. As an Object/Relational Mapping (ORM) framework, Hibernate is concerned with data persistence as it applies to relational databases (via JDBC).
Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. Hibernate’s primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual result set handling and object conversion. Applications using Hibernate are portable to supported SQL databases with little performance overhead.
In addition to its own “native” API, Hibernate is also an implementation of the Java Persistence API (JPA) specification. As such, it can be easily used in any environment supporting JPA including Java SE applications, Java EE application servers, Enterprise OSGi containers, etc.
Hibernate supports lazy initialization, numerous fetching strategies and optimistic locking with automatic versioning and time stamping. Hibernate requires no special database tables or fields and generates much of the SQL at system initialization time instead of at runtime. Hibernate consistently offers superior performance over straight JDBC code, both in terms of developer productivity and runtime performance.
Hibernate was designed to work in an application server cluster and deliver a highly scalable architecture. Hibernate scales well in any environment: Use it to drive your in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands. Hibernate is well known for its excellent stability and quality, proven by the acceptance and use by tens of thousands of Java developers.
Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotations.
Read below java tutorials for understanding various concepts involved into hibernate.
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.
Save a parent and its child entities with one persist() call in Hibernate 7. See cascade PERSIST and MERGE, the helper method that sets both sides, managed and detached parents, getReference(), and the real SQL and errors.
Add full-text search to a Spring Boot 4 application with Hibernate Search 8.4 and Lucene: map the entity, register the analyzer as a Spring bean, index existing rows on ApplicationReadyEvent, and expose a paged, sorted REST search endpoint tested with MockMvc.
Soft delete rows with Hibernate’s @SoftDelete: see the UPDATE that replaces DELETE, choose the DELETED, ACTIVE or TIMESTAMP strategy, read and restore deleted rows with native SQL, and avoid unique constraint errors.
Hibernate tutorials for Hibernate 7.4, Jakarta Persistence 3.2 and Java 25, grouped as a learning path: setup, entities, entity states, associations, queries, caching, validation, search and fixes for common errors.
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().
Hibernate maps LocalDate, LocalDateTime, Instant, OffsetDateTime and ZonedDateTime to SQL date, time and timestamp columns without annotations. See the DDL and stored values on Hibernate 7.4 and how @TimeZoneStorage keeps or drops the offset.
Set up Ehcache 3 as the Hibernate 6 and 7 second level cache: the hibernate-jcache and jakarta Ehcache dependencies, the JCache properties, a minimal ehcache.xml, @Cacheable and @Cache, hit statistics, and the startup error each missing piece causes.
“Unable to locate persister” (Unknown entity type in Hibernate 7) means Hibernate has no mapping for the class it received. See each cause reproduced on Hibernate 7.4 and Spring Boot 4.1, from javax imports and missing registration to DTOs, proxies and entity scanning, with a tested fix for each.
Hibernate Validator CDI lets the CDI container create the ValidatorFactory and Validator. Learn to inject them with Weld SE, use @Inject inside a ConstraintValidator, and get automatic method validation on CDI beans.
UnexpectedTypeException (HV000030) means a Bean Validation constraint sits on a type it cannot check, such as @NotBlank on an Integer. See every cause with the real message, a type-to-constraint grid, and the fix for numbers, dates, lists, Optional and your own types.
Validate Java objects with Hibernate Validator 9.1 and Jakarta Validation 3.1: built-in and custom constraints, messages, nested objects, groups, records, method validation and automatic checks in Hibernate ORM 7.
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.
Hibernate throws GenericJDBCException: could not prepare statement when the driver rejects the SQL and gives no SQLState to classify it. See the real messages from SQLite, H2 and HSQLDB on Hibernate 7.4, how to read the root SQLException, and the fix for each cause.
Hibernate 4.3 to 5.2 throw QueryException: Cannot mix named and positional parameters when a stored procedure call registers parameters by name and by position. See the message in each version, what Hibernate 7.4 does with mixed HQL and native queries, and the fix.
HSQLDB throws “data exception: invalid character value for cast” when text reaches a number column. See the four real causes in Hibernate 7.4 and the fix for each.
@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.
A JPA native DELETE query runs plain SQL with executeUpdate(). Learn createNativeQuery() and @NamedNativeQuery, foreign key errors and their fixes, and why callbacks, cascades and @SoftDelete are skipped.
Hibernate 3.6 to 4.1 stop at startup with NotYetImplementedException when a named native query has no resultClass or resultSetMapping. See the real error, the @ColumnResult workaround and how Hibernate 7 returns scalar values.
A JPA native UPDATE query runs our own SQL with executeUpdate() and returns the row count. Learn createNativeQuery() and @NamedNativeQuery, why loaded entities go stale, and how to declare the changed tables.
A JPA native query sends our own SQL to the database and still returns managed entities, scalar values, Tuples or records. Learn createNativeQuery(), @NamedNativeQuery, result set mappings, joins and paging with Hibernate 7.
A Hibernate criteria query builds SQL from Java objects with CriteriaBuilder, CriteriaQuery and Root. Learn filters, joins, fetch joins, group by, subqueries, pagination, dynamic filters, bulk updates and the static metamodel in Hibernate 7, with the generated SQL for each query.
Hibernate Query Language (HQL) queries entities and attributes instead of tables and columns. Learn HQL select, joins, join fetch, aggregates, subqueries, update, delete and insert in Hibernate 7, with the SQL Hibernate generates for each query.
Hibernate’s @Immutable annotation stops UPDATE statements for an entity, blocks changes to a collection and, since Hibernate 7, fails HQL update queries by default. We compare it with updatable = false, read-only queries, @Subselect and records.
A reference of the JPA annotations used on almost every Hibernate entity, from @Entity and @Column to @Embedded, @Version and @Convert, each with the DDL Hibernate 7.4 generates for it.
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 save(), update() and saveOrUpdate() were deprecated in Hibernate 6 and removed in Hibernate 7. We run the old methods on Hibernate 6.6, then show how persist() and merge() replace them for new, detached and managed entities.
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.
Hibernate association mappings link entities with @OneToOne, @ManyToOne, @OneToMany and @ManyToMany. Learn which side owns the foreign key, what mappedBy does, the default fetch types and which mapping to pick.
The four Hibernate entity states (transient, managed, detached, removed), the EntityManager method behind each transition, the SQL it sends in Hibernate 7.4, and how to check the state of an object in code.
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.
Spring throws “Bean property ‘configurationClass’ is not writable” when XML written for Hibernate 3 sets configurationClass on a newer LocalSessionFactoryBean. See the real error on Spring 7, the XML fix, and the Spring Boot 4 setup that needs no SessionFactory bean.
NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider means a Hibernate 3 class (Spring’s orm.hibernate3 factory bean or an old Ehcache provider) runs with Hibernate 4 or newer. Here is the fix for old projects and the Hibernate 7 JCache setup.
NoClassDefFoundError: org/hibernate/engine/SessionFactoryImplementor means a class built for Hibernate 3, usually Spring’s orm.hibernate3 transaction manager, runs with Hibernate 4 or newer. Find the jar, switch to the matching Spring package or align the Hibernate modules, and unwrap the SPI interface on Hibernate 7.
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.