[英]Constraint validator to validate a field in Child class based on another field in Parent class
I have 2 Domain classes like ParentClass
and ChildClass
. 我有2个Domain类,例如
ParentClass
和ChildClass
。 (ParentClass contains a list of Child class objects in Array list.) (ParentClass在“数组”列表中包含子类对象的列表。)
I created separate Validator classes for ParentClass and ChildClass to do the custom validations. 我为ParentClass和ChildClass创建了单独的Validator类来执行自定义验证。
Example validator class for the Parent class: Parent类的示例验证器类:
public class ParentClassValidator implements
ConstraintValidator<ValidatedByParentClassInterface, ParentClass> {
and then override the isValid()
method of ConstraintValidator
, 然后覆盖
ConstraintValidator
的isValid()
方法,
@Override
public boolean isValid(final ParentClass parentClass,
final ConstraintValidatorContext constraintValidatorContext) {
Example validator class for the Child class: 子类的示例验证器类:
public class ChildClassValidator implements
ConstraintValidator<ValidatedByChildClassInterface, ChildClass> {
and then override the isValid()
method of ConstraintValidator
, 然后覆盖
ConstraintValidator
的isValid()
方法,
@Override
public boolean isValid(final ChildClass childClass,
final ConstraintValidatorContext constraintValidatorContext) {
//No option to pass Parent class object here?
One of the fields in my Child class need to be validated based on the value of the field in Parent class. 需要根据Parent类中该字段的值来验证Child类中的一个字段。 But the
isValid()
method of ConstraintValidator( https://docs.oracle.com/javaee/7/api/javax/validation/ConstraintValidator.html ) has only 2 arguments so how do I pass the ParentClass object here in my ChildClassValidator? 但是ConstraintValidator( https://docs.oracle.com/javaee/7/api/javax/validation/ConstraintValidator.html )的
isValid()
方法只有两个参数,因此如何在ChildClassValidator中传递ParentClass对象?
or Should I use a for
loop in my ParentClassValidator to validate this scenario? 还是应该在ParentClassValidator中使用
for
循环来验证这种情况?
Looks like using a for
loop in my ParentClassValidator to validate this scenario is the only possible solution 似乎在我的ParentClassValidator中使用
for
循环来验证这种情况是唯一可能的解决方案
So, instead of having 2 validators ie 1 for parent class and 1 for chid class, it is better to put all the custom validations(including child class validations) in the parent class validator 因此,最好不要将2个验证器(对于父类使用1个,对于chid类使用1个),最好将所有自定义验证(包括子类验证)放入父类验证器中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.