Our Blog. We have some things we'd like to share.

Using the Hibernate API to Inspect Mapped Classes

For my current project we needed to audit the property setters Hibernate was using on our objects to make sure that any logic in them was not overly state dependent. More about this issue in Hibernate is available here. We have fairly rich object models, and a lot of methods, including setters, are never used by Hibernate. We wanted a report of the setters actually used by Hibernate to limit the amount of code we had to examine.

The Hibernate API allows you a lot of access to its configuration object model, and this is ideal for finding out how Hibernate is interacting with your code. I wrote a small class to do this inspection. The method below is run after a Hibernate Configuration object named creatively as “configuration” has been built with mapping files:

public Map findSetters() throws MappingException
{
  Map classToSetters = new HashMap();
  Iterator classMappingIterator =   configuration.getClassMappings();

  while(classMappingIterator.hasNext())
  {
    PersistentClass persistentClass = (PersistentClass)classMappingIterator.next();
    Class mappedClass = persistentClass.getMappedClass();
    Iterator propertyIt = persistentClass.getPropertyIterator();
    List classSetters = new LinkedList();

    classToSetters.put(mappedClass, classSetters);

    while(propertyIt.hasNext())
    {
      Property property = (Property)propertyIt.next();
      Setter setter = property.getSetter(mappedClass);

      classSetters.add(setter.getMethodName());
    }
  }
  return classToSetters;
}

I have uploaded a Java project that contains the full HibernateInspector class, as well as some sample classes and mappings. Un-tar it, and run

ant -Dhibernate.home="path to hibernate 3" 

to build and run the example.

Tagged:

Leave a Response

Cincinnati 513.298.1865

Virginia 7875 Promontory Court Dunn Loring, VA 22027

Kentucky 12910 Shelbyville Road Suite 310 Louisville, KY 40243 502.245.6756

© 2010 Mission Data