I want to execute this query in JPA.But i am getting error while executing this query.How to use Month(),Year() in JPA We can use these in native SQL Query.But how to use i
Dears,
sometimes we have to think with different way, maybe this can help:
TypedQuery<Number> query = entityManager.createQuery(
"SELECT SUM(COALESCE(p.amount, 0)) FROM Payment p WHERE p.paymentDate BETWEEN ?1 AND ?2", Number.class);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, month -1);
calendar.set(Calendar.YEAR, year);
query.setParameter(1, calendar.getTime());
//the location is very important
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.MILLISECOND, -1);
query.setParameter(2, calendar.getTime());
return query.getSingleResult().doubleValue();
DataNucleus JPA jhas built in support for YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, as well as the JPA 2.1 standard "FUNCTION" for invoking native functions in the RDBMS.
In my experience ALL JPA implementations support such things, unlike the impression given by the other answer
Few JPA implementations have built-in support for date/time functions.
EclipseLink
EclipseLink supports EXTRACT allowing any database supported date/time part value to be extracted from the date/time. The EXTRACT function is database independent, but requires database support.
EXTRACT(YEAR, model.currencyExchangeDate)
, but it requires EclipseLink 2.4.x
FUNC allows for a database function to be call from JPQL. It allows calling any database functions not supported directly in JPQL.
To call the DB function MyFunc(a, b, c)
use FUNC('MyFunc', a, b, c)
.
You can try FUNC('YEAR', currencyExchangeDate)
to call 'YEAR' function.
Hibernate
In HQL, you can have date function YEAR(date)
, MONTH(date)
, DAY(date)
to extract required details.
Other time functions supported are HOUR(date)
, MINUTE(date)
, SECOND(date)
.
Criteria API
CriteriaBuilder#function() : Create an expression for the execution of a database function.
CriteriaQuery<IptExchangeratelines> cq = cb.createQuery(IptExchangeratelines.class);
Root<IptExchangeratelines> exRateLine = cq.from(IptExchangeratelines.class);
cq.where(cb.equal(cb.function("year", Integer.class,
exRateLine.get(exRateLine_.currencyExchangeDate)), year)
.and(cb.equal(cb.function("month", Integer.class,
exRateLine.get(exRateLine_.currencyExchangeDate)), month)));