I have 2 tables Account and Group both contain data in a hierarchy.
Example - (Just for reference I am using PostgresSQL)
Group
|------|----------|-------------------|
| id | name | parent_group_id |
|------|----------|-------------------|
| 1 | Group1 | null |
| 2 | Group2 | 1 |
| 3 | Group3 | 2 |
| 4 | Group4 | 1 |
|------|----------|-------------------|
Account
|----|----------|----------|
| id | name | group_id |
|----|----------|----------|
| 1 | Account1 | 1 |
| 2 | Account2 | 1 |
| 3 | Account3 | 2 |
| 4 | Account4 | 3 |
| 4 | Account5 | 4 |
-----|----------|-----------
This account and group hierarchy can be many levels deep. I want to fetch all groups and accounts in an efficient way using Spring and Hibernate.
I want the output to be like -
{"name":"Group1","groups":[{"name":"Group4","groups":[],"accounts":[{"name":"Account5"}]},{"name":"Group2","groups":[{"name":"Group3","groups":[],"accounts":[{"name":"Account4"}]}],"accounts":[{"name":"Account3"}]}],"accounts":[{"name":"Account2"},{"name":"Account1"}]}
I have checked some articles but they are not recursive (means group inside a group and so on).