JSR 303 - checking multiple internal lists

I use JSR 303 and wrote some annotations, so I am familiar with the process of working with user constraints.

I just ran into a problem that I'm not sure I can solve elegantly. Objects are here to illustrate! So I have a grandparent object that has a list of children. Each child has his own list of children (obviously, grandchildren of grandparents). The size of this list can be limited with @Size. But I need to limit the TOTAL size of the number of (large) children from grandparents so that if I check a copy of my grandparents, they are limited to 50 grandchildren in all their children. An odd example, I know :-)

I started this by creating a method in grandparent that simply counts all the items in the child list lists of the child lists in GrandParent and adds a simple @Size annotation to them. It seems a little ugly - adding a method like this that should only be present for verification. Wasn't this part of what JSR was supposed to solve?

Or - create a custom annotation as follows:

@CustomListSize(listName="children.children", min=0, max=50) Grandparent --> List<Child> children @Size(min=0, max=5) -->List<Child> children --> List<Object> list1 -->List<Object> list2 

I can obviously get this with reflection / propertydescriptor and check the min / max value. Does this sound normal or is there a better way in JSR 303 that I am missing. This also works, but requires more code and is still not perfect.

Finally, what if I wanted to do the same check on the number of entries in list2? I cannot repeat CustomListSize, so how do I do this - is there an internal list?

thanks

Chris

+4
source share
2 answers

I think a custom validator for your grandparent object would be a good approach.

 @InnerListSize(lists = {"list1", list2"}, min=0, max=50) class GrandParent{ List list1; List list2; } 

Reflection can be used to get lists. Once we get them, it's easy to calculate the total size. The validation class will not be particularly complicated.

+1
source

Create your own validator for grandparents

public class GrandParentValidator inventory ConstraintValidator {

 @Override public boolean isValid(GrandParent bean, ConstraintValidatorContext ctx) { //Count the number of Grandkids int noOfGrandKids = 0 ; for (Children child :bean.getAllChild() ){ noOfGrandKids += child.getAllChild().size ; } if (int noOfGrandKids > 50){ ctx.disableDefaultConstraintViolation(); ctx.buildConstraintViolationWithTemplate("Invalid -More than 50 Grandkids found").addConstraintViolation(); return false ; } return true ; } 

}

0
source

All Articles