Video in progress

Strong Middle 🐻 Hibernate and JPA

In a `JOINED` inheritance hierarchy, what SQL does an HQL bulk `delete` or `update` turn into?

Because one entity is split across several tables, Hibernate can't do the job in a single SQL statement. It first collects the matching ids into a temporary table (or a CTE, depending on the dialect), then deletes from each table separately. So such queries are slower than expected and produce more SQL.

📖 Answer

@Entity @Inheritance(strategy = InheritanceType.JOINED)
abstract class Payment { @Id Long id; Instant createdAt; }

@Entity class CardPayment extends Payment { String maskedPan; }
@Entity class CashPayment extends Payment { String cashier; }
em.createMutationQuery("delete from Payment p where p.createdAt < :d")
  .setParameter("d", cutoff)
  .executeUpdate();

createdAt is only in the payment table, but the card_payment and cash_payment rows must be deleted too, respecting the FK order. Hibernate does roughly this:

insert into HT_payment(id) select p.id from payment p where p.created_at < ?;
delete from card_payment where id in (select id from HT_payment);
delete from cash_payment where id in (select id from HT_payment);
delete from payment where id in (select id from HT_payment);

On PostgreSQL, Hibernate 6 often does this with a single query using a CTE; other databases use a temporary table. You can see which strategy it is in the SQL log.

The practical consequences: writing to a temporary table is itself heavy at large volume; in some environments (a read-only replica, no permission to create temp tables) such a query fails. In big cleanup jobs on this kind of hierarchy, I either write the native SQL myself in the right order, or put on delete cascade on the FKs and delete only from the parent table.

With SINGLE_TABLE this problem doesn't exist: one table, one DELETE.