Search code examples
javahibernatespring-data-jpahibernate-criteria

nested exception is java.lang.IllegalArgumentException: Parameter value [2020-04-20] did not match expected type [java.util.Date (n/a)]]


I want to send this request http://localhost:8080/{url}?start=2020-04-20&end=2020-04-24&status=success&status=failed

In Transaction model

private java.sql.Timestamp addedOn;

I am trying to create a dynamic query for multiple filters following this blog: https://attacomsian.com/blog/spring-data-jpa-specifications

Specs.java file toPredicate method

if (criteria.getOperation().equals(SearchOperation.GREATER_THAN)) {
                predicates.add(builder.greaterThan(
                        root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.LESS_THAN)) {
                predicates.add(builder.lessThan(
                        root.get(criteria.getKey()), criteria.getValue().toString()));
}

Here is my Controller code

Timestamp start = new Timestamp(dateFormat.parse(request.getParameter("start")).getTime());
Timestamp end = new Timestamp(dateFormat.parse(request.getParameter("end")).getTime());
Specs txnSpecs = new Specs();
txnSpecs.add(new SearchCriteria("addedon", start, SearchOperation.GREATER_THAN_EQUAL));
txnSpecs.add(new SearchCriteria("addedon", end, SearchOperation.LESS_THAN_EQUAL));
txnSpecs.add(new SearchCriteria("status", Arrays.asList(request_params.get("status")), SearchOperation.IN));
List<Transaction> txnList = transactionRepository.findAll(txnSpecs);
return txnList;        

But when I make request I get:

nested exception is java.lang.IllegalArgumentException: Parameter value [2020-04-20] did not match expected type [java.util.Date (n/a)]]

Do I need to convert the Date value before I send it as param for the SQL query? Or I need to use other types of Date?


Solution

  • Do I need to convert the Date value before I send it as param for the SQL query?

    No, the opposite is true, you must keep it a Date but you convert it to a String by calling criteria.getValue().toString().