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.

del.icio.us:Using the Hibernate API to Inspect Mapped Classes digg:Using the Hibernate API to Inspect Mapped Classes spurl:Using the Hibernate API to Inspect Mapped Classes wists:Using the Hibernate API to Inspect Mapped Classes simpy:Using the Hibernate API to Inspect Mapped Classes newsvine:Using the Hibernate API to Inspect Mapped Classes blinklist:Using the Hibernate API to Inspect Mapped Classes furl:Using the Hibernate API to Inspect Mapped Classes reddit:Using the Hibernate API to Inspect Mapped Classes fark:Using the Hibernate API to Inspect Mapped Classes blogmarks:Using the Hibernate API to Inspect Mapped Classes Y!:Using the Hibernate API to Inspect Mapped Classes smarking:Using the Hibernate API to Inspect Mapped Classes magnolia:Using the Hibernate API to Inspect Mapped Classes segnalo:Using the Hibernate API to Inspect Mapped Classes gifttagging:Using the Hibernate API to Inspect Mapped Classes

Leave a Reply