简体   繁体   中英

Filtering in query using JPA in java

How to fetch data on the basis of YEAR using openjpa from database. I have a timestamp(RECEIPT_DATE) field in my database. Now i went to fetch the data from the database on the basis of selected year. Query is as below:

select contact_names from contact where YEAR(RECEIPT_DATE)='2014'.

This works perfectly in database.

The same i wrote in JPA like this.

select contactNames from contact where year(receiptDate)='2014'.

But i get an error like Year Arguement cannot be recognized. Is there any way to how can i perform the same query using JPA preferably not making use of any additional plugins for the same. Please guide.

You should use the JPA Criteria API Queries. They have functions to extract the year of a date. and it's helpful because if you make a mistake you know it on compile time instead on runtime.

JPA does not have the YEAR function, with JPA you will use JPQL and not SQL.

You could use NativeQuery instead:

entityManager.createNativeQuery("select * name from person", RESULT_CLASS.class);

http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html

JPA 2.1 has FUNCTION(funcName, args) and you can set the FUNCTION to YEAR (or whatever your RDBMS supports). It has no specific functions for date components, so you have to look up the specific native functions used by your RDBMS and put them into JPA2.1 "FUNCTION"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM