Video in progress

Which indexes does your Hibernate mapping call for, and how do you find the missing ones?

Neither Hibernate nor PostgreSQL creates an index on foreign key columns automatically, yet every lazy load and collection read does a where on exactly that column. So every @ManyToOne FK, frequently used filter+sort combinations and unique business keys need an index. I find the missing ones with pg_stat_statements, EXPLAIN and a query that checks the FKs.

📖 Answer

Think about what SQL each mapping produces:

@OneToMany(mappedBy = "order")
private List<OrderItem> items;

order.getItems() becomes select ... from order_item where order_id = ?. If order_item.order_id has no index, opening every order reads the whole table. On a small table you won't notice; at 50 million rows every screen takes seconds. When you delete the parent row, the database also looks for this column for the FK check.

The indexes you usually need:

  • every FK column (order_item.order_id, order.customer_id);
  • filter + sort in derived queries and @Query: findByStatusOrderByCreatedAtDesc becomes (status, created_at desc);
  • @NaturalId and unique business keys (email, SKU): a unique index;
  • with soft delete, a partial index: where deleted = false;
  • for keyset pagination, the sort columns + id.

Finding missing FK indexes:

select c.conrelid::regclass as tbl, a.attname as fk_col
from pg_constraint c
join pg_attribute a on a.attrelid = c.conrelid and a.attnum = c.conkey[1]
where c.contype = 'f'
  and not exists (select 1 from pg_index i
                  where i.indrelid = c.conrelid and i.indkey[0] = c.conkey[1]);

Then in pg_stat_statements I take the queries with the most total time and look at them with EXPLAIN (ANALYZE, BUFFERS). A Seq Scan on a big table is a candidate.

Redundant indexes hurt too: every INSERT/UPDATE has to update them. I periodically review the ones with idx_scan = 0 in pg_stat_user_indexes. I write indexes in a Flyway migration, not with Hibernate's @Index annotation, because on prod a big table needs create index concurrently.