I am trying to use Predicate to build a query. Here is my entity:
public class MyEntity {
private LocalDateTime date;
private Integer amount;
//Some other
}
I also have a class that contains my criteria
public class EntityCriteria
private LocalDateTime fromDate;
private LocalDateTime toDate;
private Integer minAmount;
private Integer maxAmount;
//Other properties and getters/setters
}
To avoid having add manually a predicate for each criteria (1) Because there are a lot 2) So I can add a criteria without having to add its predicate), I run through list of criteria need to check (date, amount,...) and then I have a configuration file to tell if I need to use equal, between or something else and, in the case of between, the name of the lower and upper criteria in EntityCriteria.
criteriaList.forEach(criteria -> {
String strategy = getStrategyFromCriteria(criteria);
String field = getEntityFieldFromCriteria(criteria);
switch(strategy) {
case "between":
String lowerCriteriaName = getLowerCriteria(criteria)
String upperCriteriaName = getUpperCriteria(criteria)
// Something like lowerValue = getValueFromName(lowerCriteriaName)
// Something like upperValue = getValueFromName(upperCriteriaName)
Predicate predicate = cb.between(root.get(field), lowerValue, upperValue)
});
I have no issue with equal since it asks an Object as parameter but equals need the type of the matching attribue in MyEntity and I can't figure how to do it in a way where it could take LocalDateTime or Integer in the same code. I would need something like a dynamic cast and be able to declare lowerValue and upperValue no matter the type.
Do you have any idea?