Peter Penzov
Peter Penzov

Reputation: 1588

Parameter value [2018-04-08T11:02:44] did not match expected type [java.util.Date (n/a)]

I want to send this XML to rest api server:

XML Request:

<reconcile>
  <start_date>2018-04-08T11:02:44</start_date>
  <end_date>2018-04-08T11:02:44</end_date>
  <page>1</page>
</reconcile>

JAXB code:

@XmlRootElement(name = "reconcile")
@XmlAccessorType(XmlAccessType.FIELD)
public class Reconcile {

    @XmlElement(name = "start_date")
    @XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
    public LocalDateTime start_date;
    @XmlElement(name = "end_date")
    @XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
    public LocalDateTime end_date;
    @XmlElement(name = "page")
    public String page;

SQL query:

public List<PaymentTransactions> transactionsByDate(LocalDateTime start_date, LocalDateTime end_date) throws Exception {

        String hql = "select e from " + PaymentTransactions.class.getName() + " e where e.created_at >= ? and e.created_at <= ?";
        Query query = entityManager.createQuery(hql).setParameter(0, start_date).setParameter(1, end_date));
        List<PaymentTransactions> paymentTransactions = (List<PaymentTransactions>) query.getResultList();
        return paymentTransactions;
    }

But when I make request I get:

java.lang.IllegalArgumentException: Parameter value [2018-04-08T11:02:44] 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 use other type of Date?

Upvotes: 11

Views: 56318

Answers (2)

coladict
coladict

Reputation: 5095

Because you use createQuery and JPQL, the expected type is determined during parsing, and the one you've specified in the PaymentTransactions class is java.util.Date.

Just change the type of created_at inside the PaymentTransactions class to LocalDateTime. It's fully supported by Hibernate's recent versions.

Upvotes: 9

Jesper
Jesper

Reputation: 206816

You are setting start_date, which is a LocalDateTime, as the parameter for the SQL; the error message tells you it wants a java.util.Date, and that it does not understand a LocalDateTime object. You'll need to convert it:

Date startDate = Date.from(start_date.atZone(ZoneId.systemDefault()).toInstant());
Date endDate = Date.from(end_date.atZone(ZoneId.systemDefault()).toInstant());

Query query = entityManager.createQuery(hql)
                  .setParameter(0, startDate).setParameter(1, endDate));

(This is assuming that you're using java.time.LocalDateTime and that you want to use the default time zone of your system).

This is necessary because JPA / Hibernate does unfortunately not (yet) automatically understand the relatively new java.time classes (it requires you to use the old java.util.Date class).

Upvotes: 15

Related Questions