Skip to content

Instantly share code, notes, and snippets.

@Abhi-Codes
Last active September 30, 2022 05:45
Show Gist options
  • Save Abhi-Codes/b2e67a380f88b8b19c4e9cae6fe2eaff to your computer and use it in GitHub Desktop.
Save Abhi-Codes/b2e67a380f88b8b19c4e9cae6fe2eaff to your computer and use it in GitHub Desktop.
Create Predicate dynamically based on type and operator
private BooleanExpression getPredicate(String key, String operator, String value, PathBuilder<?> entityPath,
Class<?> classType) {
boolean isMultiValue = value.contains(",");
Class<?> propertyType = getPropertyType(classType, key);
switch (propertyType.getSimpleName()) {
case "Integer":
if (isMultiValue) {
NumberPath<Integer> path = entityPath.getNumber(key, Integer.class);
Integer[] numValue = Stream.of(value.split(",")).map(Integer::parseInt).toArray(Integer[]::new);
return getNumberPredicate(path, operator, numValue);
} else {
NumberPath<Integer> path = entityPath.getNumber(key, Integer.class);
Integer numValue = Integer.parseInt(value);
return getNumberPredicate(path, operator, numValue);
}
case "Long":
if (isMultiValue) {
NumberPath<Long> path = entityPath.getNumber(key, Long.class);
Long[] numValue = Stream.of(value.split(",")).map(Long::parseLong).toArray(Long[]::new);
return getNumberPredicate(path, operator, numValue);
} else {
NumberPath<Long> path = entityPath.getNumber(key, Long.class);
Long numValue = Long.parseLong(value);
return getNumberPredicate(path, operator, numValue);
}
case "Double":
if (isMultiValue) {
NumberPath<Double> path = entityPath.getNumber(key, Double.class);
Double[] numValue = Stream.of(value.split(",")).map(Double::parseDouble).toArray(Double[]::new);
return getNumberPredicate(path, operator, numValue);
} else {
NumberPath<Double> path = entityPath.getNumber(key, Double.class);
Double numValue = Double.parseDouble(value);
return getNumberPredicate(path, operator, numValue);
}
case "Boolean":
if (":".equals(operator)) {
return entityPath.getBoolean(key).eq(Boolean.parseBoolean(value));
} else {
throw new RuntimeException("Unsupported Boolean operation");
}
case "String":
return getStringPredicate(key, operator, value, entityPath);
case "LocalDate":
return getDatePredicate(key, operator, value, entityPath);
case "LocalDateTime":
return getDateTimePredicate(key, operator, value, entityPath);
default:
// do nothing
return null;
}
}
private BooleanExpression getNumberPredicate(NumberPath<Integer> path, String operator, Integer value) {
switch (operator) {
case ":":
return path.eq(value);
case ">":
return path.gt(value);
case "<":
return path.lt(value);
case ">=":
return path.goe(value);
case "<=":
return path.loe(value);
case "!=":
return path.notIn(value);
default:
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment