Let’s say I have a table called Person with the columns:
id, name, parent_id
and let’s say I have some data like this:
1, Bob, null
2, Mary, 1
3, Tim, 1
4, Sally, 3
So Bob has 2 kids: Mary and Tim.
And Tim has 1 kid: Sally (who grandparent is Bob)
What is the easiest way to write a JPA query such that I could find all descendants of Bob? (i.e. the result would return Mary, Tim and Sally)
I don’t think you can do this with plain JPA.
But if you can modify your table like this
and your data will look like this
then you can query for all the descendants using like clause.
For example:
here 1 – is parentPath + entityId, so for Bob like clause looks like
because Bob’s parentPath is null and Bob’s id is 1.
And for Sally the query will look like this
because Sally’s parentPath is ‘1/3’ and Sally’s id is 4.
if you have to add a new child you just need to set its parent_path to