Tuesday, February 24, 2015

Use Reflection for Spring Data Jpa Specification to enable filter on all attributes of entities

Problem:

We have a large number of domain entities that we want to expose to front end. Front end would like the users to be able to filter on those entities using almost all attributes that those entities have.

Also, when the entities form one to one or one to many relations, the users should be able to filter on the attributes of the related entities as well.

If we use Spring Data JpaRepository interface, we can filter entities using Query Methods:


However if the User entity has 5 attributes, then there are 31 possible combinations of those 5 attributes that the user should be able to filter the results, which means 31 methods have to be defined. And we have to decide which method to be invoked in the controller class based on URL parameters. It will be the same situation using @query.

Solution:

So instead we have to use JpaSpecificationExecutor for our repositories and pass a Specification instance to the findAll() method of entity repositories. We create a BaseSpecification class to transform url filter parameters into predicats.

First we try to make every attribute of the entities filterable. To do that, we have to read the attribute name from the url query string and test whether the query key is one of the entity's attributes. We achieve this by using the Reflection API:
But we also want to be able to filter on attributes from the entities that are associated with the entity to be filterd. We design the api as such: http://localhost:8080/demo/api/user?address.street=5th will find all users whose address has the attribute Street and has the value 5th.

At this point the front end rises the requirement that the legacy front end code couldn't provide the entity name that is associated with the entity to be filtered. So the to find the users whose address has attribute street and value 5th, the query string looks like this: http://localhost:8080/demo/api/user?street=5th

In this case we have to search if the url query key is one of the attributes from the filtered entity or from entities associate with it. We can achieve this search using either Breadth First Search or Depth Firsts Search.


Here the search output a Pair. The Path object is later to be used to build the Criteria Predicate. And the Class object tells us the type of the attribute used for filtering. If the type is Date for example, we can generate Date specific Criteria Predicates.

No comments:

Post a Comment