wasAsked.

How would you model hierarchical categories efficiently with SQL, JPA, and Hibernate?

Zomato · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, JPA, SQL

Community answers

Posted by wasAsked editorial collection

Choose a model based on query patterns. For product categories (small, read-heavy, rarely changed), simple models with caching usually win. 1. Adjacency list — the default @Entity public class Category { @Id @GeneratedValue private Long id; private String name; @ManyToOne(fetch = FetchType.LAZY) private Category parent; @OneToMany(mappedBy = "parent") private List<Category> children = new ArrayList<>(); } - Simple inserts and moves (change parent). - Subtree and ancestor queries need recursion: a recursive CTE in a native query (WITH RECURSIVE in PostgreSQL and MySQL 8). Hibernate 6 also supports CTEs in HQL. - Avoid recursive lazy loading of children in loops (N+1 at every level). For small trees, load all categories in one query and build the tree in memory, then cache it. 2. Materialized path - Store a path string such as /1/4/17/ (plus a depth column). - Subtree: WHERE path LIKE '/1/4/%' (indexable prefix match); ancestors are the IDs in the path; breadcrumbs are easy. - Moving a subtree requires updating descendants' paths. PostgreSQL's ltree extension provides operators and GiST indexes for this model. 3. Closure table - A separate table category_closure(ancestor_id, descendant_id, depth) containing every ancestor-descendant pair. - Very fast queries for descendants, ancestors and depth; supports efficient "products in this category including all subcategories" joins. - Writes are more complex (insert many pairs per node), and moving subtrees requires deleting and re-inserting pairs. Map it as a separate entity or use native queries. 4. Nested sets - Left and right numbers per node allow subtree queries with simple range conditions, but inserts and moves renumber many rows. Rarely the best choice for frequently edited trees. Practical recommendation - Use an adjacency list plus an in-memory or Redis cache of the whole category tree, invalidated when admins edit categories. - If product listing needs "category and all subcategories" in SQL, add a materialized path or closure table, or precompute descendant ID lists and query products WHERE category_id IN (:ids). Integrity rules - Prevent cycles when moving nodes (a node cannot become its own descendant), index parent_id, optionally limit depth, and define what happens to products when a category is deleted (reassign or block deletion).

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics