0

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

  • Can you post the logs as well? Or at least where is the error is thrown, line etc – Sir. Hedgehog Oct 04 '18 at 10:59
  • What are you passing for Date as the parameter value? – robot_alien Oct 04 '18 at 11:05
  • [LocalDate between using JPA 2.1 Criteria API](https://stackoverflow.com/questions/47928424/localdate-between-using-jpa-2-1-criteria-api). And [Compare Date entities in JPA Criteria API](https://stackoverflow.com/questions/9449003/compare-date-entities-in-jpa-criteria-api). Did you use your search engine? It will often give you an answer much faster than anyone can type one here on Stack Overflow. – Ole V.V. Oct 04 '18 at 11:28

1 Answers1

0

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

Lai
  • 472
  • 6
  • 23