title: Hierarchical Data Fetch in Spring and Hibernate
body: <p>I have 2 tables Account and Group both contain data in a hierarchy.</p>
  
  <p>Example - 
  (Just for reference I am using PostgresSQL)</p>
  
  <p>Group</p>
  
  <pre><code>|------|----------|-------------------|
  |  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        |
  -----|----------|-----------
  </code></pre>
  
  <p>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.</p>
  
  <p>I want the output to be like - </p>
  
  <pre><code>{"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"}]}
  </code></pre>
  
  <p>I have checked some articles but they are not recursive (means group inside a group and so on).</p>