0

Requirement: Fetch a product given by name and all the materials required to build that product.

Given: A MYSQL table named product_entries with columns like id, product_name, product quantity, material_name, material_quantity.

So for an example let's say to construct 1 table I would need 4 legs, 1 bottom-base, 1 upper-base. And further to construct, 1 bottom-base I would need few bb-part1, bb-part2, and bb-part3, and so on, for upper-base. The entries look likes below:

enter image description here

So, if the user gives a table as an input, he should get a tree that has a table and all the children under it, that is table will have legs, bottom-base, and upper-base; bottom-base will have bb-part1, bb-part2, and bb-part3 under it and upper-base will have ub-part1 under it.

To achieve this, I followed this post where it was given how to construct a tree with N number of children. But the problem that I face is that my ouput only contains elements at level 1.

My logic looks like below:

public void getAllPartsForMaterial(final String partNumber) {

    if (partNumber == null || partNumber.trim().isEmpty()) {
        throw new IllegalArgumentException("Invalid part number received");
    }

    Node<ItemDTO> root = new Node<>(ItemDTO.builder().partNumber(partNumber).build());

    getParts(root, partNumber);
    System.out.println(root.getChildren());
}

private void getParts(Node<ItemDTO> root, final String partNumber) {

    List<Material> materials = materialRepository
        .findAllByProduct(partNumber);

    if(!materials.isEmpty()) {
        materials.forEach(material -> {

            Node<ItemDTO> child = new Node<>(ItemDTO.builder()
                .partNumber(material.getMaterial())
                .quantity(material.getMaterialQuantity())
                .build());

            root.addChild(child);

            getParts(child, material.getMaterial());
        });
    }
}

So my output is like:

[Node{data=ItemDTO(partNumber=legs, quantity=4.0)}, Node{data=ItemDTO(partNumber=bottom-base, quantity=1.0)}]

How can add all elements in this tree, can someone tell what am I missing?

Loui
  • 533
  • 17
  • 33
  • Seems to me like you need a [hierarchical query](https://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/). – Abra Nov 02 '19 at 09:44
  • It seems to be a good solution, but I am looking to find a solution, not on the database side. – Loui Nov 02 '19 at 09:58

0 Answers0