REST Query Language with Spring and JPA Criteria Date type

434 views Asked by At

I am using the following code to make a dynamic search by 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;
}

but when I pass a Date type parameter I got the following error:

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

Can anyone pls show me an implementation to handle dates as well. Thanks

1

There are 1 answers

0
Lai On

Ensure you haven't stripped down your parameter to a String. See if you can avoid using the .toString()