user3419507
user3419507

Reputation: 117

How to compare date in a jpql query

Hi I want to list all the current records in my database where the date belong to the current month.

where d.jourvisite BETWEEN :startDate AND :endDate

this is my function

    public List<Visite> getvisiteDétaillé() {
    Calendar MyEnddate;
    MyEnddate = Calendar.getInstance();
    MyEnddate.add(Calendar.MONTH, 1);
    TypedQuery<Visite> query;
    query =
    em.createQuery("SELECT v FROM Visite v JOIN v.datevisiteList d where d.jourvisite BETWEEN :startDate AND :endDate", Visite.class);
    query.setParameter("startDate",Calendar.getInstance().getTime());
    query.setParameter("endDate",MyEnddate,TemporalType.DATE);
    System.out.println("date actual"+Calendar.getInstance().getTime());
    System.out.println("date After 30 days"+MyEnddate.getTime());
    return query.getResultList();
}

I'm sure that i have some records in the DB that are suitable for the query but when I display the result nothing to display with no syntax error

Upvotes: 2

Views: 8924

Answers (1)

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

In the javadoc for TemporalType.DATE they mention:

Map as java.sql.Date.

but you are passing in a Calendar for endDate parameter.

Just pass in the Date instance like you do for the startDate parameter:

query.setParameter("endDate", MyEnddate.getTime());

PS You should follow the most used naming conventions to make the code more readable.

Upvotes: 1

Related Questions