I have an Employee/User table as shown below:
I want to update the HIERARCHY column as follows:
How can I achieve using Spring Boot, JPA, and Java.
I have an Employee/User table as shown below:
I want to update the HIERARCHY column as follows:
How can I achieve using Spring Boot, JPA, and Java.
@naveen.gupta
I am not expert in Java but what you can apply this pseudocode in batch process in any language. It is a recursive function
FUNCTION - EMP_HIERARCHY_SET
For Given User: EMP_1
Run EMP_HIERARCHY_SET for each records.
It is not efficient but I assume this is a one time activity post that any new employee hierarchy can be easily created by picking his managers “HIERARCHY” column and appending “~EMP_ID” to it.
Apart from this, there are some libraries which actually does the same in some frameworks. Assuming these are employee records, there is limit to a number of employees. Therefore, this should be executed pretty fast despite having an order of O(n2)
@naveen.gupta You can also achieve the same with the below query
employee
To update the hierarchy column in the employee table based on the manager_id and emp_id reference, you can use a recursive CTE (Common Table Expression) in PostgreSQL. Here is an example query:
WITH RECURSIVE employee_hierarchy AS (
SELECT emp_id, manager_id, emp_id AS hierarchy
FROM employee
WHERE manager_id IS NULL -- Assuming NULL manager_id represents top-level employees
UNION ALL
SELECT e.emp_id, e.manager_id, eh.hierarchy || '/' || e.emp_id
FROM employee e
INNER JOIN employee_hierarchy eh ON e.manager_id = eh.emp_id
)
UPDATE employee e SET hierarchy = eh.hierarchy
FROM employee_hierarchy eh
WHERE e.emp_id = eh.emp_id;
This query uses a recursive CTE called employee_hierarchy
to traverse the employee table recursively, starting from the top-level employees (those with a NULL manager_id). It concatenates the emp_id values with the hierarchy path from the higher-level employees.
Then, the UPDATE statement updates the hierarchy column in the employee table by joining it with the employee_hierarchy
CTE using the emp_id.
Please note that you need to replace the table and column names (employee
, emp_id
, manager_id
, hierarchy
) with the actual names used in your database schema.