Error using CURRENT_TIMESTAMP() into a query

2019-09-16 02:48发布

问题:

I want to compare two date in jpql query using the current date function

I got an error

Syntax error parsing [SELECT d FROM Dossier d WHERE d.depid=1 AND d.typeDossier = :tpd AND d.dateCreation < CURRENT_TIMESTAMP() + 5].
[105, 107] The left expression is not an arithmetic expression

This is my query:

public List<Dossier> getDossierFindAllParDepartementDBTECHandUrgen() {
    return (List<Dossier>) em.createQuery("SELECT d FROM Dossier d WHERE d.depid=1 AND d.typeDossier = :tpd AND " +
        "d.dateCreation < CURRENT_TIMESTAMP() + 5",
                                          Dossier.class).setParameter("tpd", "Urgent").getResultList();
}

回答1:

JPA supports function CURRENT_TIMESTAMP

https://en.wikibooks.org/wiki/Java_Persistence/JPQL#Functions

but will not work with arithmetic operations. You can solve the problem by using a parameter, for example

TypedQuery<Dossier> query = em.createQuery("SELECT d FROM Dossier d WHERE d.depid=1 AND d.typeDossier = :tpd AND " +
        "d.dateCreation < :fiveDaysAhead",
                                          Dossier.class);
Date myFiveDaysAhead = new Date(Calendar.getInstance().add(Calendar.DAYS_OF_YEAR,5).getTimeInMillis());//or something
query.setParameter("tpd", "Urgent");
query.setParameter("fiveDaysAhead", myFiveDaysAhead, TemporalType.TIMESTAMP);

It may also be possible to find vendor specific solutions, as i noticed in one other answer https://stackoverflow.com/a/18514326/2835455