Skip to content
Advertisement

How to query a Hierarchical Category tree entity with undefined depth

I have created a hierachy structure or a tree structure for a shopping site using springboot. My problem is how to query such a structure when looking for a specific product and its parents:

JavaScript

This is what i have done, any pointers on what i need to do on the entity to achieve this structure and also how i can query it i.e

It is also important to note that i am using postgres database

  1. findAllProducts in a category and
  2. find all categories linked to a product.

Category Entity

JavaScript

Product Entity

JavaScript

Category Service

JavaScript

Product Service

JavaScript

Advertisement

Answer

You can use a recursive query to select the parents of a given category.

JavaScript

Following is a test that creates the category hierarchy and queries it:

JavaScript

Note that this was tested on H2 and PostgreSQL databases. You might need to modify the native query according to the actual database you are using.

PostgreSQL has excellent documentation on how this works, see:

https://www.postgresql.org/docs/11/queries-with.html

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement