【发布时间】:2012-10-27 05:48:02
【问题描述】:
使用休眠验证器的验证在标记为@Transient 和@NotNull 的字段上失败。
然而,它只对那些已经存储在数据库中但现在在对象树中遍历的对象失败。 (因为它们的值当然是 null)
对于这样的实体:
public class User {
@ManyToMany
@Fetch(org.hibernate.annotations.FetchMode.JOIN)
@Valid
private Set<Role> roles;
@NotNull
private String someField;
}
public class Role {
@ManyToMany
@Fetch(org.hibernate.annotations.FetchMode.JOIN)
@Valid
private Set<User> users;
}
当我验证User 并且有更多用户使用特定Role 我有问题,即使当前用户验证成功,对于其他用户我也会出错。
在将数据提交到服务器端之前,我会在客户端进行此验证。
我看到了一些解决@Transient 和@NotNull 验证问题的想法:
但是这些并没有涵盖我的情况(在相关对象上存在违规行为)。而且我还没有遇到服务器端的验证问题:)。至于测试那将是下一步。
所以问题是,有什么方法可以解释验证器,即在验证期间应该跳过从数据库获取的传递对象?
我正在考虑通过覆盖来扩展我当前使用的JPATraversableResolver:
/**
* Determine if the Bean Validation provider is allowed to reach the property state
*
* @param traversableObject object hosting <code>traversableProperty</code> or null
* if validateValue is called
* @param traversableProperty the traversable property.
* @param rootBeanType type of the root object passed to the Validator.
* @param pathToTraversableObject path from the root object to
* <code>traversableObject</code>
* (using the path specification defined by Bean Validator).
* @param elementType either <code>FIELD</code> or <code>METHOD</code>.
*
* @return <code>true</code> if the Bean Validation provider is allowed to
* reach the property state, <code>false</code> otherwise.
*/
boolean isReachable(Object traversableObject,
Path.Node traversableProperty,
Class<?> rootBeanType,
Path pathToTraversableObject,
ElementType elementType);
但是,我仍然面临确定要检查哪些属性以及不检查哪些属性的问题。 如果我的检查是针对当前持久对象的瞬态字段,我不会涵盖持久实体(2 个相关实体)的情况,其中检查将针对其中一个,而另一个将有问题的瞬态字段。
有什么想法吗?有这方面的经验吗?
【问题讨论】:
标签: java hibernate jpa validation