I have a requirement (which seems a usual one), understanding it by example
-----------------------
Dependant-----------------------
Code:
@Min.List( {
@Min(value = 0, groups = { CreateChecks.class }),
@Min(value = 1, groups = { UpdateChecks.class, DeleteChecks.class,
ParentCUDChecks.class }) })
@Max(value = 0, groups = { CreateChecks.class })
@Id
private int id;
@MappedValid(source = { CreateChecks.class, UpdateChecks.class,
DeleteChecks.class, Default.class }, target = {
ParentCUDChecks.class, ParentCUDChecks.class,
ParentCUDChecks.class, Default.class })
@NotNull(groups = { CreateChecks.class, UpdateChecks.class })
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false, updatable = false)
private Employee employee;
------------------------
------------------------
------------------------
Employee------------------------
Code:
@Min.List( {
@Min(value = 0, groups = { CreateChecks.class }),
@Min(value = 1, groups = { DeleteChecks.class, UpdateChecks.class,
ParentCUDChecks.class }) })
@Max(value = 0, groups = { CreateChecks.class })
@Id
@GeneratedValue(generator = "userIdGen")
@SequenceGenerator(name = "userIdGen", initialValue = 1, allocationSize = 1, sequenceName = "SEQ_CAMPAIGN_USER_ID")
private int id;
-------------------------
ValidationUtilCode:
public void validate(Object target, Class group) {
Set<ConstraintViolation<Object>> constraintViolations = validator
.validate(target, group);
if (constraintViolations.size() != 0) {
throw new ConstraintViolationException((Set) constraintViolations);
}
validateMappedValid(target, group);
}
private void validateMappedValid(Object target, Class group) {
List<Field> mappedValidFields = new LinkedList<Field>();
Field[] fields = target.getClass().getFields();
for (Field field : fields) {
MappedValid validAnnot = field.getAnnotation(MappedValid.class);
if (validAnnot != null) {
if (validAnnot.source().length == validAnnot.target().length) {
for (int i = 0; i < validAnnot.source().length; i++) {
if (validAnnot.source()[i] != null
&& validAnnot.source()[i].equals(group)) {
validate(target, validAnnot.target()[i]);
break;
}
}
}
}
}
}
If you use JPA entities there is a common requirement that
1- If you update/delete an entity then id of the entity should be greater than 0 and ids of all manytoone associated entities should be greater than 0
2- If you create an entity then id of the entity should be equal to 0 and ids of all manytoone associated entities should be greater than 0
For above requirement simple @Valid will not work i have to define a mapping for source validation group to target validation group. I have defined a custom annotation for this and then above code validates recursively. Since annotation do not have maps so i have to use two arrays.
Code:
@MappedValid(
source = { CreateChecks.class, UpdateChecks.class, DeleteChecks.class, Default.class },
target = { ParentCUDChecks.class, ParentCUDChecks.class, ParentCUDChecks.class, Default.class }
)
Any comments?