Assuming that this code is indeed a performance culprit and needs to be optimized (as per Ilja's recommendation), you'll need to provide more of the algorithm to us. You have nested loops, resulting in nested queries. This is generally best avoided, but without knowing the actual queries, that's the best we can do.
As an example of a simple optimization, think about loading a standard tree structure. As I found it, the structure was basic: each node had its parent node's ID. Given the root node's ID, the method to load the tree was to find all that node's children and recursively load from there. If the tree had 50 nodes, this resulted in 50 queries, each returning a few nodes at a time (and none for the leaves).
The solution I chose was to add the root node's ID to every node. Now loading the tree involved one query for all nodes and then a simple loop in
Java to build a tree from the nodes. While the algorithm to build the tree looked much like the original algorithm, reducing the query down to one cut the total time by 95%-98%, depending on the size of the tree (larger trees approached 99% savings).
Perhaps there is a way to perform joins to minimize the nesting of queries, but we'll need more information to know.