具有Spring和JPA Criteria Date类型的REST查询语言

时间:2018-10-04 10:54:28

标签: java date jpa jpa-criteria

我正在使用以下代码通过Criteria API进行动态搜索

public List<User> findAllByParam(List<SearchCriteria> params) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<User> query = builder.createQuery(User.class);
    Root<User> r = query.from(User.class);

    Predicate predicate = builder.conjunction();

    for (SearchCriteria param : params) {


        if (param.getOperation().equals(">")) {
            predicate = builder.and(predicate,
                    builder.greaterThan(r.get(param.getKey()),
                            param.getValue().toString()));
        } else if (param.getOperation().equals("<")) {
            predicate = builder.and(predicate,
                    builder.lessThan(r.get(param.getKey()),
                            param.getValue().toString()));
        } else if (param.getOperation().equals(":")) {
            predicate = builder.and(predicate,
                    builder.equal(r.get(param.getKey()), param.getValue()));
        }
    }
    query.where(predicate);

    List<User> result = entityManager.createQuery(query).getResultList();
    return result;
}

但是当我传递日期类型参数时,出现以下错误:

"Parameter value [1539122400000] did not match expected type [java.util.Date (n/a)]"

任何人都可以向我展示一个也可以处理日期的实现。谢谢

1 个答案:

答案 0 :(得分:0)

确保没有将参数简化为字符串。看看是否可以避免使用.toString()