• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • Frits Walraven
  • Himai Minh

Improving An Algorithm

Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm looking for a Better Way (tm) than a method I'm using.

This algorithm is in a Hibernate ResultTransformer implementation, but I don't think this question is Hibernate specific so I'm asking it here.

The query is for an Organization, with some basic fields such as id, name, etc. However, the Organization also contains a Collection of child Organizations, which seriously impacts performance when building the hierarchy recursively (especially considering Hibernate many-to-one/one-to-many relationships with Organization).

In order to improve performance, I implemented the Nested Set model, where each item has a "left" and "right" value. To get all of the children of an organization, I simply query for results between its own left and right values.

However, I'm thinking the method I'm using to rebuild the hierarchy could stand improvement, and am open to suggestions.

Upon the initial return of the query results, I store everything in a Map<String, Object>. This is converted to a List<Map><String, Object>> by Hibernate.

I then create two more maps:
Map<Organization, Integer> childParentMap - maps the organization to the id of its parent.
Map<Integer, Organzation> organizationIdToObjectMap - maps the unique id of the object to the object.

Using these two maps, I can get the id of the parent from the childParentMap, then turn around and get the parent object itself from the organizationIdToObjectMap. Unfortunately, this requires an initial pass through the List<Map><String, Object>> to build the organizationIdToObjectMap and the childParentMap, then a second pass through the organizationIdToObjectMap to build the hierarchy.

The code involved is below.

My gut feeling is that there has to be a more efficient way to do this. Any ideas?

    Bookmark Topic Watch Topic
  • New Topic