I have currently implemented a dynamic query builder that works perfectly if my query conditions are spelled correctly. Since this might not be always the case I need a solution that is flexible enough to take any variation of the condition, primarily supporting case insensitivity.
Current specification's toPredicate method override code looks like this:
final List<Predicate> predicates = new ArrayList<Predicate>();
Path<String> username = root.get("username");
Path<String> agentCode = root.get("agentCode");
Path<EntityStatus> status = root.get("status");
Path<String> firstname = root.get("firstName");
Path<String> lastname = root.get("lastName");
Path<String> email = root.get("eMail");
if(criteria.getUsername()!=null && !criteria.getUsername().isEmpty()) {
predicates.add(cb.equal(username, criteria.getUsername()));
}
if(criteria.getAgentCode()!=null && !criteria.getAgentCode().isEmpty()) {
predicates.add(cb.equal(agentCode, criteria.getAgentCode()));
}
if(criteria.getFirstName()!=null && !criteria.getFirstName().isEmpty()) {
predicates.add(cb.like(firstname, "%"+criteria.getFirstName()+"%"));
}
if(criteria.getLastName()!=null && !criteria.getLastName().isEmpty()) {
predicates.add(cb.equal(lastname, criteria.getLastName()));
}
if(criteria.getEMail()!=null && !criteria.getEMail().isEmpty()) {
predicates.add(cb.equal(email, criteria.getEMail()));
}
if(criteria.getStatus()!=null) {
predicates.add(cb.equal(status, criteria.getStatus()));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
And my repository interface that is being called from the service layer looks like this.
public interface UserRepo extends PagingAndSortingRepository<User, Long> {
List<User> findAll(Specification spec);
}