tags:

views:

45

answers:

2

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.

A: 

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).

Pascal Thivent
Hi! I am using Toplink Essentials for the same. Please help, if any function exists in Toplink. Thanks.
venomrld
+1  A: 

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)

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.

James
Hi James, Thanks for your answer. I am actually using toplink essentials. I applied the way as above bu still I get:Unexpected Token - FUNC.Please Help!
venomrld
@venomrld As James wrote, this FUNC stuff is available EclipseLink 2.1+, see [Bug 300512](https://bugs.eclipse.org/bugs/show_bug.cgi?id=300512). So don't expect to find it in TopLink Essentials.
Pascal Thivent
So I'm stuck. Please help if some way exists. I'm using netbeans 6.5 and visual faces for development. Seems I've to change pretty much code to migrate.
venomrld