Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate recursive query

My desired query is to get a list of Course objects that belong to a Category. My objects are as follows:

public class Course{
     String name;
     List<Category> categories;
}

public class Category{
     String name;
     Category parent;
}

Since the categories reference each other, they can have an infinite depth:

A
  A.A
     A.A.A
     A.A.B
  A.B
     A.B.A
B
 B.A
 B.B
C

How can I query for courses within the category "A.A", and return all Courses associated with A.A, A.A.A, and A.A.B?

like image 478
KevMo Avatar asked Aug 19 '10 19:08

KevMo


1 Answers

If you are willing to use native SQL and your database supports recursive common table expressions (basically all major DBMS except MySQL) it's pretty easy:

WITH RECURSIVE course_tree (name) AS (
   SELECT name
   FROM course
   WHERE name = 'A.A'
   UNION ALL
   SELECT name
   FROM course
   WHERE parent_id = course_tree.id
)
SELECT *
FROM course_tree
like image 117
a_horse_with_no_name Avatar answered Oct 03 '22 23:10

a_horse_with_no_name