JPA Query MONTH/YEAR functions

社会主义新天地 提交于 2019-12-17 18:51:31

问题


How can I write a JPA query using MONTH function just like sql query?

@NamedQuery(name="querybymonth", query="select t from table1 t where MONTH(c_Date) = 5")

When I use the above pattern for query, I get an error: unexpected token - MONTH.


回答1:


If you are using EclipseLink (2.1) you can use the FUNC() function to call any database function that is not defined in the JPA JPQL spec.

i.e. FUNC('MONTH', c_Date)

In JPA 2.1 (EclipseLink 2.5) the FUNCTION syntax becomes part of the specification (and replaces the EclipseLink-specific FUNC).

If you are using TopLink Essentials, you cannot do this in JPQL, but you can define a TopLink Expression query for it (similar to JPA 2.0 criteria), or use native SQL.

Also if you are using any JPA 2.0 provider and using a Criteria query there is a function() API that can be used to define this.




回答2:


I want to query YEAR(itemDate) but the function doesn't exit, then i saw the SUBSTRING() function so what i did was Select q from table where SUBSTRING(itemDate, 1, 4)='2011' and it works for me! hope it helps!

if you need you a dynamic variable, you can do that too. here :poDate is the year which is deifned in the setParameter();

@NamedQuery(name = "PurchaseOrders.findByYear", query = "SELECT p FROM PurchaseOrders p WHERE SUBSTRING(p.poDate, 1, 4) = :poDate")

Query q = em.createNamedQuery("PurchaseOrders.findByYear");
q.setParameter("poDate", s_year+"");

but if your okay with your solutions, that'll be fine. i just find JPA faster to execute.




回答3:


The MONTH() function exists in Hibernate HQL but is not a standard JPA function. Maybe your JPA provider has some proprietary equivalent but you didn't mention it. If it doesn't, fall back on native SQL.


I am using Toplink Essentials for the same. Please help, if any function exists in Toplink. Thanks.

To my knowledge, TopLink doesn't have a direct equivalent. So either use a native SQL query or maybe a TopLink Expression query (not sure about this, and not sure this is available in TopLink Essentials).




回答4:


Following worked for me with hibernate (4.3.9.Final) & JPA 2.1.

@NamedQuery(name = "PartyEntity.findByAID", query = "select distinct psc.party from PartyShortCode psc where (psc.shortCode = :aidNumber or FUNCTION('REPLACE',psc.accountReference,' ','') = :aidNumber) and psc.sourceSystem in :sourceSystem")



来源:https://stackoverflow.com/questions/3674567/jpa-query-month-year-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!