If you have spent enough years maintaining enterprise JPA applications, two scars are probably etched into your memory: staring at a baffling ConstraintViolationException caused by Hibernate flushing a DELETE after an INSERT on the same unique key, and realizing halfway through a 200,000-row batch job that your EntityManager persistence context just ate 4 GB of heap.
On November 12, 2026, Hibernate ORM 8.0.0.CR1 landed alongside Hibernate Reactive 5.1.0.CR1—implementing Jakarta Persistence 4.0 and Jakarta Data 1.1 while attacking both of those classic pain points directly in the core engine. Even better for day-to-day productivity, IntelliJ IDEA 2026.3 just shipped a dedicated Hibernate 8 Debugger with live HQL replay and automatic N+1 query detection.
In this deep dive—building on our earlier Spring Databases posts on Spring Data JPA & Java Records and JPA Auditing—we will unpack EntityAgent, see how Hibernate 8’s default graph-based flush coordinator kills ordering bugs, wire up native PostgreSQL Row-Level Security (RLS) for airtight multi-tenancy, and wrap up with a practical sidebar on PostgreSQL 19’s new built-in REPACK (CONCURRENTLY) command.
1. Jakarta Persistence 4.0: EntityAgent and Statement vs. TypedQuery
For over a decade, Hibernate developers who needed lightweight, zero-dirty-checking persistence for batch pipelines or high-throughput REST endpoints reached for Hibernate’s proprietary StatelessSession. Jakarta Persistence 4.0 standardizes that exact concept across the entire specification as EntityAgent.
| Capability | Classic EntityManager | New JPA 4.0 EntityAgent |
|---|---|---|
| First-Level Cache / Persistence Context | Stateful; tracks managed entities and runs dirty checking on flush | Stateless; no automatic dirty checking or managed entity graph in memory |
| SQL Execution Timing | Deferred until flush/commit | Explicit, immediate insert(), update(), delete(), upsert() |
| Lazy Loading | Transparent proxies within open session | Explicit fetching (fetch(...) / entity graphs)—eliminates accidental N+1 cascades |
| Best Fit | Rich domain models with complex object graphs | Batch ETL, high-throughput microservices, stateless Spring REST/gRPC handlers |
JPA 4.0 also fixes one of JPA’s oldest API paper cuts by cleanly separating read queries (TypedQuery) from mutating bulk statements (Statement / StatementOrTypedQuery), adds @PostCreate / @PreClose persistence-unit lifecycle callbacks, supports package- and module-level @EntityListeners (in package-info.java and module-info.java), and introduces programmatic SQL ResultSet mappings.
package com.ghostprogrammer.persistence;
import jakarta.persistence.EntityAgent;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Statement;
import java.time.Instant;
import java.util.List;
public class InvoiceBatchArchiver {
private final EntityManagerFactory emf;
public InvoiceBatchArchiver(EntityManagerFactory emf) {
this.emf = emf;
}
public int archiveSettledInvoices(List<InvoiceRecord> records, Instant cutoff) {
// Stateless EntityAgent: zero persistence-context bloat across large batches
try (EntityAgent agent = emf.createEntityAgent()) {
agent.getTransaction().begin();
for (InvoiceRecord record : records) {
agent.insert(record);
}
// JPA 4.0 cleanly separates mutating Statements from read-only TypedQuery
Statement cleanup = agent.createStatement(
"delete from PendingInvoice p where p.settledAt < :cutoff");
cleanup.setParameter("cutoff", cutoff);
int removed = cleanup.execute();
agent.getTransaction().commit();
return removed;
}
}
}
Alongside JPA 4.0, Hibernate 8 implements Jakarta Data 1.1 via Hibernate Data Repositories—complete with compile-time static queries, @Select projections, and stateful/async repository support.
2. Goodbye Ordering Hacks: Graph-Based Flush Coordination (Default in 8.0)
Historically, Hibernate flushed pending operations in a fixed heuristic order (INSERTs → UPDATEs → collection deletions → collection inserts → DELETEs). That heuristic worked 95% of the time and blew up spectacularly the other 5%—most infamously when replacing a child entity sharing a UNIQUE natural key, forcing developers to sprinkle ugly manual entityManager.flush() calls in the middle of business logic.
In Hibernate 8, graph-based flush coordination is now the default. Before emitting SQL, Hibernate builds a relational constraint dependency graph modeling:
- Foreign key dependencies across entities
- Unique constraints
- Secondary and optional tables
- Mixed entity and collection mutations
Hibernate topologically sorts the graph so deletes, updates, and inserts execute in an order that satisfies your actual database constraints—no manual .flush() gymnastics required. (If you encounter a legacy edge case during migration, hibernate.flush.queue.type=legacy remains available temporarily as a fallback toggle.)
Bonus Core-Engine Upgrades in Hibernate 8
- Bulk Subselect Fetching for To-One Associations (
FetchMethod.BY_SUBQUERY): Extends subselect batch loading beyond collections to@ManyToOne/@OneToOneassociations, curbing N+1 query storms without massiveJOINrow multiplication. - Opt-In Runtime Bidirectionality Management: Enabling
hibernate.bidirectionality_management=trueautomatically synchronizes inverse associations during flush preparation without triggering lazy collection initialization. @Filter&@SQLRestrictionon To-One Associations: Now supported directly on@ManyToOneand@OneToOnerelationships.- Graduated JSON/XML Functions & Skinny
hibernate-bom: Database JSON/XML query functions and SQL AST/translator@SPIcontracts graduate out of incubation, joined by a newStatementObserverhook and skinny BOM.
3. Native PostgreSQL Row-Level Security (RLS) for Multi-Tenancy
Discriminator-based multi-tenancy (@TenantId) in Hibernate 6 and 7 was already convenient—Hibernate appended AND tenant_id = ? automatically to HQL and Criteria queries. The catch? Any native SQL query, reporting view, or forgotten ad-hoc join bypassed Hibernate’s filter, turning one missing WHERE clause into a cross-tenant data leak.
Hibernate 8 integrates discriminator multi-tenancy directly with native database Row-Level Security (RLS) on PostgreSQL, Db2, SQL Server, and CockroachDB—enforcing tenant isolation inside PostgreSQL itself so not even a buggy native query can read another tenant’s rows.
Step 1: Enable PostgreSQL RLS Policy
CREATE TABLE customer_orders (
id UUID PRIMARY KEY,
tenant_id TEXT NOT NULL,
order_total NUMERIC(12, 2) NOT NULL
);
ALTER TABLE customer_orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE customer_orders FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_policy ON customer_orders
USING (tenant_id = current_setting('app.current_tenant', true))
WITH CHECK (tenant_id = current_setting('app.current_tenant', true));
Step 2: Declare @TenantId in Java and Wire the Tenant Context
@Entity
@Table(name = "customer_orders")
public class CustomerOrder {
@Id
private UUID id;
@TenantId
@Column(name = "tenant_id", nullable = false, updatable = false)
private String tenantId;
@Column(name = "order_total", nullable = false)
private BigDecimal orderTotal;
// constructors, getters
}
With Hibernate 8’s RLS integration active, your CurrentTenantIdentifierResolver supplies the tenant ID (for example, extracted from a Spring Security JWT claim or a Java 25 ScopedValue), and Hibernate binds the PostgreSQL session/transaction variable (SET LOCAL app.current_tenant = ...) automatically whenever a connection participates in a tenant transaction. Defense-in-depth at both the ORM layer and the PostgreSQL storage engine—zero extra boilerplate per query.
4. Database Operations Sidebar: PostgreSQL 19’s Built-In REPACK (CONCURRENTLY)
If you run multi-tenant Hibernate workloads on PostgreSQL, there is another huge database milestone making waves right now: PostgreSQL 19’s native REPACK command.
Because PostgreSQL uses MVCC, heavy UPDATE and DELETE churn leaves behind dead tuples. Autovacuum marks that space reusable internally, but it never returns disk space to the operating system. Historically, reclaiming OS disk space meant choosing between VACUUM FULL (which takes an ACCESS EXCLUSIVE lock and freezes all production traffic) or installing external extensions like pg_repack.
PostgreSQL 19 brings online table compaction straight into core Postgres:
-- Reclaim table bloat and return space to the OS online with minimal locking
REPACK CONCURRENTLY customer_orders;
-- Reclaim space AND physically cluster rows by tenant/date index online
REPACK CONCURRENTLY customer_orders USING INDEX idx_customer_orders_tenant_created;
Paired with PostgreSQL 19’s parallel autovacuum index cleanup and pg_plan_advice for stabilizing execution plans without code changes, high-churn Spring + Hibernate PostgreSQL tables become dramatically easier to operate at scale.
Conclusion
Hibernate 8 is far more than a routine Jakarta EE version bump. Between stateless EntityAgent batch performance, default graph-based flush ordering that ends manual .flush() hacks, native PostgreSQL Row-Level Security for multi-tenancy, and IntelliJ IDEA 2026.3’s new Hibernate 8 Debugger, the Java persistence stack is sharper and safer than it has ever been. Note that Spring Boot 4.2 currently ships on Hibernate 7.4 (JPA 3.2), so test Hibernate 8.0.0.CR1 in sandbox branches now as Jakarta EE 12 and next-generation Spring Data integration come into focus.
Discover more from GhostProgrammer - Jeff Miller
Subscribe to get the latest posts sent to your email.

