Ashish Thukral
Ashish Thukral

Reputation: 1485

Hibernate Validator for proxied collection

I was trying to use the hibernate @Size validation on a OneToMany collection which is lazy initialized. If i am creating the parent entity with the children added in this collection, the validation is applied on trying to persist. But if i simply find the parent entity and then do a getChildren(), the validation is not applied at all. I even tried putting the annotation on the getter. so i am using @Size(max=1) but still hibernate doesn't throw any exception even if children are more than 1. even EAGER fetch does not help. As of now i had to put validation logic myself in the getter but obviously this is not the clean way. kindly let me know if someone has faced this issue before and if there is any elegant way of doing this.

Upvotes: 1

Views: 245

Answers (2)

Hardy
Hardy

Reputation: 19109

Event based validation is triggered on persist, update and remove. These are the events JPA defines for Bean Validation to occur (refer to the JSR-317 and JSR-338 specifications for more details). There is no validation when loading entities/associations from the database. The assumption is that persisted data is already validated. If you need to validate in your scenario, you need indeed to validate manually.

Upvotes: 1

Serhii Shevchyk
Serhii Shevchyk

Reputation: 39436

Hibernate Validator provides two TraversableResolvers out of the box which will be enabled automatically depending on your environment. The first is DefaultTraversableResolver which will always return true for isReachable() and isTraversable(). The second is JPATraversableResolver which gets enabled when Hibernate Validator is used in combination with JPA 2.

Create your own implementation of TraversableResolver or use DefaultTraversableResolver and configure Hibernate Validator.

public class MyTraversableResolver implements TraversableResolver {

    @Override
    public boolean isReachable(
            Object traversableObject,
            Node traversableProperty,
            Class<?> rootBeanType,
            Path pathToTraversableObject,
            ElementType elementType) {
        return true;
    }

    @Override
    public boolean isCascadable(
            Object traversableObject,
            Node traversableProperty,
            Class<?> rootBeanType,
            Path pathToTraversableObject,
            ElementType elementType) {
        return true;
    }
}

Upvotes: 1

Related Questions