I need to know how to call a SQL function like HOUR() in a @NamedQuery in Java Persistence.
To make it simpler, In a table that has a starttime (TIMESTAMP) column, I need to get the rows that have the startime falling between CURRENT_TIMESTAMP and HOUR(CURRENT_TIMESTAMP)+1. I have spent a day on Google and still did not manage to find a answer.

The following query works when tried with JAVADB, however the same fails in @NamedQuery.

Java DB Instance:

    select e.EMPLOYEEID, e.FIRSTNAME, r.STARTTIME, r.ENDTIME from reservation r, employee e
where e.EMPLOYEEID = r.EMPLOYEEID AND HOUR(r.STARTTIME) = HOUR(CURRENT_TIMESTAMP)

@NamedQuery:

    @NamedQuery(name="reservation.getcurrent",query = "select e.EMPLOYEEID, e.FIRSTNAME,
r.STARTTIME, r.ENDTIME from reservation r, employee e where e.EMPLOYEEID = r.EMPLOYEEID
AND HOUR(r.STARTTIME) = HOUR(CURRENT_TIMESTAMP)")

ERROR:

[2014-04-22T17:03:00.946+0530] [glassfish 4.0] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=38 _ThreadName=admin-listener(5)] [timeMillis: 1398166380946] [levelValue: 1000] [[
  Exception while deploying the app [LyndaPortalReservation] : Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [LyndaPortalReservationPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing [select e.EMPLOYEEID, e.FIRSTNAME, r.STARTTIME, r.ENDTIME from reservation r, employee e where e.EMPLOYEEID = r.EMPLOYEEID AND HOUR(r.STARTTIME) = HOUR(CURRENT_TIMESTAMP)]. 
[126, 169] The right expression is not a valid expression.]]
有帮助吗?

解决方案

For clarity, I have added the exact syntax for the declaring a function in JPQL. @Neil was correct but the use of double quote for FUNCTION Name did not work. The syntax for FUNCTION name was FUNC('funcName', args). We need to use single quotes. Hence for other users looking for similar answers. Here is the exact syntax.

@NamedQuery(name="reservation.getall",query = "SELECT e.employeeid, e.firstname, r.starttime, r.endtime from reservation r, employee e where e.employeeid = r.employeeid AND FUNC('HOUR', r.starttime) = FUNC('HOUR', CURRENT_TIMESTAMP)")

This helped resolve my original problem of using functions in HQL.

其他提示

JPA 2.1 allows use of "FUNCTION(funcName, args)" in a JPQL query string. Use that and set the funcName as "HOUR" (or whatever it is for the DB in question).

Use

formatter = new SimpleDateFormat("HH");
hour = formatter.format(CURRENT_TIMESTAMP);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top