Hello I'm trying to solve this problem for quite some time now. I've created a dumbed down version to make te problem space a little clearer.
I have 2 DTO objects. A parent and a child, The child should only be validated if the parent has a certain state(createChild should be true). This state is checked by the GroupSequence provider and the approptiate validation groups are added. The ChildDto Field is annotated with @ConvertGroup and @Valid.
When createChild is true on the parentDto the group gets added but the @NotEmpty constraint is never checked. so the name of the child can still be empty.
Can anyone tell me how to make this work, or if there is another solution to this problem? Thanks in advance.
I've added my code below.
The ParentDto
Code:
@GroupSequenceProvider(ParentGroupSequenceProvider.class)
public class ParentDto{
@Valid
@ConvertGroup(from= CreateChild.class,to=Creation.class)
private ChildDto childDto;
private boolean createChild;
public ChildDto getChildDto() {
return childDto;
}
public void setChildDto(ChildDto childDto) {
this.childDto = childDto;
}
public boolean isCreateChild() {
return createChild;
}
public void setCreateChild(boolean createChild) {
this.createChild = createChild;
}
}
The Child Dto:
Code:
public class ChildDto {
@NotEmpty(groups=Creation.class)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The GroupSequenceProvider:
Code:
public class ParentGroupSequenceProvider implements DefaultGroupSequenceProvider<ParentDto> {
static Logger log = Logger.getLogger(ParentGroupSequenceProvider.class.getName());
@Override
public List<Class<?>> getValidationGroups(ParentDto parentDto) {
List<Class<?>> sequence = new ArrayList<Class<?>>();
/*
* ContactDataBis must be added to the returned list so that the validator gets to know
* the default validation rules, at the very least.
*/
if (parentDto == null){
sequence.add(ParentDto.class);
return sequence;
}else {
/*
* Here, we can implement a certain logic to determine what are the additional group of rules
* that must be applied.
*/
if (parentDto.isCreateChild()) {
sequence.add(CreateChild.class);
log.info("Added CreateChild to groups");
}
sequence.add(ParentDto.class);
return sequence;
}
}
}