Thursday, July 19, 2007

Persist XMLBeans using Hibernate

I'm currently working on a project where we need to persist xmlbean objects using hibernate (well - we may choose to do so to avoid having to map from xmlbeans to POJO beans since they are both, ahem BEANS! ). This hibernate Interceptor will handle instanciation and mappings of XMLBeans

public class MyHibernateInterceptor
extends EmptyInterceptor
implements Interceptor
{
protected SessionFactory factory;

public MyHibernateInterceptor(SessionFactory factory) {
this.factory = factory;
}

public String getEntityName(Object object)
{
Class[] interfaces = object.getClass().getInterfaces();
for (int i=0;i
if (XmlObject.class.isAssignableFrom(interfaces[i])) {
return interfaces[i].getName();
}
}
return super.getEntityName(object);
}

public Object instantiate(String entityName, EntityMode entityMode, Serializable id)
{
if (EntityMode.POJO.equals(entityMode)) {
// Only load POJO style
try {
Class clazz = Class.forName(entityName);
if (XmlObject.class.isAssignableFrom(clazz)) {
Class factoryClazz = Class.forName(entityName+"$Factory");
Method newInstanceMethod = factoryClazz.getMethod("newInstance", null);
Object obj = newInstanceMethod.invoke(null, null);
setIdentity(entityName, obj, id, entityMode);
return obj;
}
} catch (Exception e) {
// Nothing to do, but to let hibernate deal with it
}
}
return super.instantiate(entityName, entityMode, id);
}

protected void setIdentity(String entityName, Object obj, Serializable id, EntityMode entityMode)
{
ClassMetadata classMetaData = factory.getClassMetadata(entityName);
classMetaData.setIdentifier(obj, id, entityMode);
}

}


And this is how I configure the lot


cfg = new Configuration().configure("hibernate.cfg.xml");
cfg.setInterceptor(new MyHibernateInterceptor(cfg.buildSessionFactory()));


later...