Video in progress

Strong Middle 🐻 Hibernate and JPA

What SQL does a polymorphic query turn into under the `TABLE_PER_CLASS` strategy, and why can't you use it with an `IDENTITY` id?

Each concrete class stores all of its columns in its own table, so select from Base becomes a UNION ALL over the subclass tables. The id must be unique across all tables, while IDENTITY gives a separate counter in each table.

📖 Answer

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
abstract class Notification {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) Long id;
    String text;
}
@Entity class SmsNotification extends Notification { String phone; }
@Entity class EmailNotification extends Notification { String email; }

select n from Notification n where n.text like :q becomes roughly:

select ... from (
   select id, text, phone, null as email, 1 as clazz_ from sms_notification
   union all
   select id, text, null, email, 2 from email_notification
) n where n.text like ?

With many subclasses, the union is big, and the database sometimes can't push the where down inside.

The id question: when you do find(Notification.class, 10), Hibernate looks for 10 in all the tables. If both SMS and email have id=10, one id matches two entities, which isn't allowed. That's why you need a shared sequence or a UUID; Hibernate rejects IDENTITY with this strategy.

In addition, if you reference Notification with a @ManyToOne, you can't put an FK in the database: which table would it point to?

In practice this strategy is rarely chosen. If you almost never need a polymorphic query, @MappedSuperclass is usually better: the common fields are inherited, but there's no polymorphism and no union.