Vishnu K Vishnu K - 1 year ago 165
Java Question

Jpa Specifications predicate for greaterThan and lesserThan conditions

i'm using spring data jpa specifiations for dynamic complex queries...

In my service layer, i create the specification like this,

SearchSpecification<User> spec = new CommonSpecification<Case>(new SearchCriteria("", ">", 6));

public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Predicate predicate = null;
switch (searchCriteria.getOperator()) {
case ">" :

Path<?> p = getPath(Integer.class, root, searchCriteria.getKey());
Expression<? extends Object> ex = getExpression(gtClazz, root, searchCriteria.getKey());

predicate = criteriaBuilder.greaterThan(ex, searchCriteria.getValue());
return predicate;

private <T, Object> Path<Object> getPath(Class<Object> clazz, Root<T> root, String key) {
String[] fields = key.split("\\.");
Path<?> path = root;
for (String field : fields) {
path = (Path<Object>) path.get(field);
return (Path<Object>) path;

private <T, R> Expression<R> getExpression(Class<R> clazz, Root<T> root, String key) {
Path<Object> path = (Path<Object>) getPath(clazz, root, key);
Expression<Class<?>> expression = path.type();
return (Expression<R>) expression;

I'm getting issues on this below line,

predicate = criteriaBuilder.greaterThan(ex, searchCriteria.getValue());

how can i use the greaterThan/LesserThan conditions using JPA Specifications.

Thanks in advance.


Answer Source

refer this link.. it will help to solve my bugs..

Create a JPA Criteria fully dynamically


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download