Jpa规范可以预测更大和更小的条件

时间:2016-08-27 07:38:19

标签: java hibernate jpa spring-data specifications

我正在使用spring数据jpa规范进行动态复杂查询...

在我的服务层,我创建了这样的规范,

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


@Override
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());
     break;
    }
    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;
}

我在下面这行遇到了问题,

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

如何使用JPA规范使用greaterThan / LesserThan条件。

提前致谢。

0 个答案:

没有答案