Hibernate version: Annotations Version: 3.2.0 CR1, 13.05.2006
I am using Hibernate Validation Annotations with Spring 2.0cr3 and the new Spring form tags. I have a collection of child EmailAddress objects that is stored in a java.util.Map. The Map field has the @Valid annotation
Code:
@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
@MapKey(name="role")
@Valid
private Map<EmailAddressRole, EmailAddress> emailAddresses
= new HashMap<EmailAddressRole, EmailAddress>();
EmailAddress defines a String emailAddress field that has the @Email annotation.
Code:
@Basic
@Email
@Length(max=255)
private String emailAddress;
If the email address is invalid, the validation catches the error fine, but it reports an incorrect path: emailAddresses[n].emailAddress where n is a random number depending on the order keys returned by emailAddresses.keys(). This makes it impossible to match the error to the offending EmailAddress instance.
The problem appears to be in ClassValidator.getInvalidValues(T, Set<Object>).
Code:
String indexedPropName = MessageFormat.format(
"{0}[{1}]",
propertyName,
INDEXABLE_CLASS.contains( element.getClass() ) ?
( "'" + element + "'" ) :
index
);
The set INDEXABLE_CLASS contains (IIRC) Integer, Long, and String. Since the key to my Map is EmailAddressRole, the contains test fails and the reported path uses the index instead of the key.
I modified the code as follows and it works for me. I have no idea if this is a general improvement or if it will break in most other circumstances. My assumption is that if the collection is a map, then the path should use the key. I know this depends on element.toString doing something useful, but when using Spring and JSPs, there's a good chance it will.
Code:
String indexedPropName = MessageFormat.format(
"{0}[{1}]",
propertyName,
map != null ?
( "'" + element + "'" ) :
index
);
Douglas