tags:

views:

575

answers:

1

I am writing a Hibernate CompositeUserType, and in order to serialize the custom object to JDBC, I need to know the name of the table I am updating (because there is some configuration for my tool attached to the table).

The only way I can make this work right now, is to explicitly parameterize my UserType with the entity tablename, which is redundant and error-prone.

Is there a way to get to this information in "nullSafeSet" ?

public void nullSafeSet(PreparedStatement ps, Object value, int index,
  SessionImplementor session) 
        throws HibernateException, SQLException {

    // find out the entity table name here

If not, is there a way to get to the owning entity's definition during the initialization of the UserType (similar to how parameters are passed)?

+1  A: 

I've done something similar where I needed to set a property on the custom type at runtime based on some other settings. Using the Configuration, you can get to the custom type to set a property dynamically like this:

for (Iterator iter=configuration.getClassMappings(); iter.hasNext();) {
  PersistentClass pc = (PersistentClass)iter.next();
  for (Iterator iter2=pc.getPropertyIterator(); iter2.hasNext();) {
    Property property = (Property)iter2.next();
    if (property.getType().getName().equals("your custom type")) {
      SimpleValue v = (SimpleValue)property.getValue();
      v.getTypeParameters().setProperty("table property", pc.getTable().getName());
    }
  }
}

Obviously, there are a lot of assumptions here (one table per entity, custom type is a single property, etc), but it should work.

Another possibility that I haven't tried is to use the PreparedStatement metadata in the nullSafeSet method, like: statement.getMetaData().getTableName(index).

Brian Deterling