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.

有帮助吗?

解决方案

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.

其他提示

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;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top