Hibernate version: 3.1
I am porting my xml mappings to Hibernate Annotations. In the current XML mappings, all the String types are replaced with my own TrimmedString UserType. This was easy enough to do for existing mappings, but as I port to Annotations, I want to make it automatic, so that I don't have to remember to specify a @type for each String property.
Based on a previous post about doing this with older versions of Hibernate, I run the following code after Hibernate has been configured.:
Code:
protected void addTrimmedTypeInMapping(Configuration configuration) throws MappingException{
for (Iterator mappings = configuration.getClassMappings(); mappings.hasNext();) {
PersistentClass mappingClass = (PersistentClass) mappings.next();
addTrimmedTypeInMappingProperty(mappingClass.getIdentifier());
for (Iterator iterator = mappingClass.getPropertyIterator();iterator.hasNext();) {
Property property = (Property) iterator.next();
addTrimmedTypeInMappingProperty(property.getValue());
}
}
}
protected void addTrimmedTypeInMappingProperty(Value value) throws MappingException{
if (value instanceof SimpleValue) {
if (org.hibernate.Hibernate.STRING.equals(value.getType())) {
((SimpleValue)value).setTypeName(TrimmedString.class.getName());
}else if(value.getType().isComponentType()){
Component component = (Component)value;
for (Iterator iterator = component.getPropertyIterator();iterator.hasNext();) {
Property property = (Property) iterator.next();
addTrimmedTypeInMappingProperty(property.getValue());
}
}
}
}
Then, just to check to make sure it is setup correctly, I can print the mapping properties:
Code:
public void printTypeMappings(Configuration cfg ) {
for (Iterator mappings = cfg.getClassMappings(); mappings.hasNext();) {
PersistentClass mappingClass = (PersistentClass) mappings.next();
System.out.println(mappingClass.getClassName());
for (Iterator iterator = mappingClass.getPropertyIterator();iterator.hasNext();) {
Property property = (Property) iterator.next();
if( property.getValue().getType() instanceof CustomType ) {
CustomType ct = (CustomType)property.getValue().getType();
System.out.println("\t" + property.getName() + "\t" + ct + "->" +ct.getReturnedClass() );
System.out.println("\t\t" + ct.getName() );
System.out.println(ct.getHashCode(ct, null));
} else {
System.out.println("\t" + property.getName() + "\t" + property.getValue().getType());
}
}
}
}
This seems to be setup correctly. Calling getHashCode on the CustomType invokes the hash code method on my TrimmedString UserType.
But when I save an object, the it doesn't make use of my TrimmedString UserType, it still uses the regular StringType.
Is there anything else I need to setup/do in order to manually register all my TrimmedString UserTypes?
Thanks,
Jon