Hey all,
I'm having an issue implementing a generic sorter for my Hibernate objects.
I have three classes:
Product Type is many-to-one to
Product is one-to-many to
Manufacturer
I have a web app which displays all Product Types in a system, and which allows you to sort from a variety of criteria, including any fields in ProductType or any fields in a Product or Manufacturer.
For example, given a bunch of Product Types, I can sort by their names, or even by the names of their Manufacturers (by traversing from a Product Type to its Product and to its Manufacturer).
To implement a generic comparator for my objects, I have a system that allows me to pass in a base class, and a dot-separated-list-of-fields. For example, I can create
Code:
ObjectFieldComparator(ProductType, "name")
to perform comparisons on ProductType.name
or
Code:
ObjectFieldComparator(ProductType, "product.manufacturer.name")
to perform comparisons on ProductType.product -> Product.manufacturer -> Manufacturer.name.
To get at the different fields within each class, I use reflection and Class.getDeclaredField on each field name, and Field.get to retrieve each field. I then iterate through that returned object, getting its associated field, etc. until I reach my end goal.
The problem I have is when a class is not yet initialized. If I use Field.get() to grab a field in a non-initialized object, it returns null, since I am not using the class's getXXX() method to grab and initialize the field in question.
I figured I could call Hibernate.isInitialized() and Hibernate.initialize() on the uninitialized objects prioir to trying to retrieve their fields, but that doesn't seem to do anything for me. Even after calling Hibernate.initialize(), the field that is returned by Field.get() is still null.
Is there a better way of creating this generic comparator class? Again, I need to be able to grab a field an arbitrary depth from a Hibernate object. The path to my final field will consist solely of Hibernate objects, which may or may not be lazily loaded.
Thanks,
Roger