jeffmaher
jeffmaher

Reputation: 1902

How to Validate a Collection of annotated objects in XML

I was looking over this post of using JSR-303 to validate a collection of objects. The solution works great with annotations, but I can't seem to get it to work with the Hibernate Validator XML formatted configuration.

For example, I have code similar to this:

public class DataSet
{
    Collection<Data> dataCollection;
    public Collection<Data> getDataCollection() {...}
}

From there, I have a custom validator/annotation DataValidator/@ValidData.

In XML, I do this first:

<bean class="DataSet"
    ignore-annotations="true">
    <field name="dataCollection">
        <valid/>
        <constraint annotation="ValidData"/>
    </field>
</bean>

However, I get the following exception:

Exception in thread "main" javax.validation.UnexpectedTypeException: No validator could be found for type: java.util.Collection<DataSet>

So I swap the <valid> tag with the <constraint> one in the XML. It seems this is not valid with the XSD schema and the XML can no longer be parsed.

<bean class="DataSet"
    ignore-annotations="true">
    <field name="dataCollection">
        <constraint annotation="ValidData"/>
        <valid/>
    </field>
</bean>

Exception in thread "main" javax.validation.ValidationException: Error parsing mapping file.

Does anyone know how I can use XML to validate this collection with must custom validator?

Upvotes: 1

Views: 1135

Answers (1)

jeffmaher
jeffmaher

Reputation: 1902

The key was adding a class-level constraint annotation in the XML to the Data POJO itself.

<bean class="DataSet"
    ignore-annotations="true">
    <field name="dataCollection">
        <valid/>
    </field>
</bean>

<bean class="Data" ignore-annotations="true">
     <class>
          <constraint annotation="ValidData"/>
     </class>
</bean>

Upvotes: 1

Related Questions