Here is a scenario: The model I need to validate has a tree-like structure. In this model, each node can be a/an remote/access-point/cluster. I have a model builder which builds the model tree given a set of nodes. The builder then hands off this tree to the validator to validate it. I have some constraints which require to check the uniqueness of a certain property for a set of nodes (e.g: all access-points in the tree must have unique serial number). These constraints are written as custom constraints. I recognize these constraints follow the same pattern which is I need to traverse the tree to collect all required node and build a multimap out of the collected nodes and check for uniqueness using the key of the current targeted object. For above example, the custom constraint is a class constraint of access-point class. I need to collect all access-points in the tree, build a multimap of <serialNumber:access-point> pairs. Then I lookup from the map the collection of access-points based on the serial number of the access-point being validated. It would be beneficial if the multimap of <serialNumber:access-point> pairs can be stored in the custom validator so that I don't need to re-do this expensive task again when validating other access-points.
Input data: The model I need to validate has a tree-like structure. In this model, each node can be a/an remote/access-point/cluster. I have a model builder which builds the model tree given a set of nodes. The builder then hands off this tree to the validator to validate it.
Requirement: I have some constraints which require to check the uniqueness of a certain property for a set of nodes of the same type (e.g: all access-points in the tree must have unique serial number). These constraints are written as custom constraints. I wrote the logic of the custom constraint as follows:
-
Starting from the root, traverse the object graph, collect all nodes of the same type (type: remote/access-point/cluster)
-
Check for the uniqueness requirement
The expensive task is the above logic is executed by the bean validation framework for each object in the object graph meaning we are traversing the whole object graph at every node.
One way to eliminate traversing the object graph in many times is to reuse the object graph from the previous validation. The logic of the customer constraint should be rewritten as follows:
-
Check if the object graph exists in the object graph validation scope
-
If not exists, Starting from the root, traverse the object graph, collect all nodes of the same type (type: remote/access-point/cluster). Store the object graph in the object graph validation scope to be reused later.
-
Check for the uniqueness requirement
|