Issue
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);
}
Solution
Normally, you achieve the case-insensitivity with using method equalsIgnoreCase().
However in this case you just parse values to be compared without implementing the comparison itself. Thus you can parse all the values in lower-case using the method toLowerCase() forcing them to be compared case insensitively.
predicates.add(cb.equal(email.toLowerCase(), criteria.getEMail().toLowerCase()));
Edit: I have taken a look on the JavaEE documentation of CriteriaBuilder and found the method lower() which may be helpful.
Answered By – Nikolas Charalambidis
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0