Fetch dates (by month or year) stored in TIMESTAMP using JPA - performance

I am facing a problem and I would like you to help me.
It turns out I have one table in my Oracle 11g database where I store failures of one electronic device. The table definition is following:
CREATE TABLE failure
( failure_id NUMERIC NOT NULL
, fecha TIMESTAMP NOT NULL
, module_id NUMERIC NOT NULL
, code NUMERIC
, PRIMARY KEY(failure_id)
);
Where 'fecha' means 'date'.
I need to fetch failures by YEAR or by MONTH for one specific module but I can't. My ORM maps the TIMESTAMP type to java.sql.Date but I don't know how to compare the month in the JPQL sentence. I have tried to use ORACLE functions with native queries but I front with another issue: to cast the results.
I am using JPA 2.0 with Eclipselink 2.3.2.
My doubts are:
Can I use Oracle functions with this version of Eclipselink library? My experience say no.
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT(YEAR FROM f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
query.setParameter(1, year);
query.setParameter(2, idModule);
I get this error: Unexpected token [(]
Can I use Eclipselink functions? My experience say no.
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT('YEAR', f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
query.setParameter(1, year);
query.setParameter(2, idModule);
Same error.
Do you know a simple way to fetch this data using only one query?
I know I can fetch one module and then check failures with loops but I think it is not the best performing solution.
Thanks.
My sources:
Eclipselink JPA functions link
Eclipselink Query Enhancements link

A native query is written in the SQL dialect of your DB so can use DB specific functionality see the createNativeQuery methods of the EntityManager.
However there is another solution, test the timestamp against a lower and upper value:
WHERE f.fecha >= '2012-9-1' AND f.fecha < '2012-10-1'

The syntax in EclipseLink 2.4 for EXTRACT is,
EXTRACT(YEAR, f.fecha)
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#Functions

I used Eclipselink v 2.4 functions and I am getting values using this:
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE SQL('EXTRACT (YEAR FROM ?)', f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2 ");
Extracting year from date stored in database avoids to me one comparison between two dates.

Use
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT(YEAR from f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");

I was facing the same problem. I only checked for the correct syntax of that EXTRACT function for oracle and it worked for me! (Notice the FROM clause into the function syntax.
#NamedQuery(name = "Registros.findByFechacaptura", query = "SELECT s FROM Registros s WHERE EXTRACT(YEAR FROM s.fechacaptura) = EXTRACT(YEAR FROM :fechacaptura)")

Related

Sum a List of averages in spring boot jpa query

I have this query thats return a list of averages
#Query("SELECT AVG(p.quantity) FROM Position p GROUP BY p.client.id") public List<Float> findAVGPositions();
But I want to return SUM of averages like this, but it doesn't work
#Query("SELECT SUM(averages) FROM (SELECT AVG(p.quantity) as averages FROM Position p GROUP BY p.client.id)") public Float findSumAVGPositions();
Can you help me? thanks
Unfortunately, in JPQL, nested selects are not permitted in FROM clause. They are allowed only in SELECT and WHERE.
You have two approaches available.
(1) Use findAVGPositions and calculate sum in Java
findAVGPositions().stream().reduce(0f, Float::sum);
(2) Use a native SQL query
#Query(value = "SELECT SUM(averages) " +
"FROM (SELECT AVG(p.quantity) AS averages " +
"FROM position p " +
"GROUP BY client_id) AS averages_select",
nativeQuery = true)
public Float findSumAVGPositions();
Depending on the database you use, AS averages_select alias might be needed or not (PostgreSQL requires it, even if it's not used).
Please, pay attention to use the correct names of a database table for Position entity and a database column for a foreign key client.id.
In my example, I assumed a standard mapping convention: position as a table name, and client_id as a foreign key column.

Optional parameter in query does not work for db2 but works in oracle

Below query works fine for Oracle database, but for Db2 it throws error sqlcode -417.
I have looked up similar problems but did not get any definitive answer:
#Query(value = "select * from tableName f where (aC is null or f.a_c = aC)", nativeQuery = true)
Page<tablename> findByFilters(String aC, Pageable pageable);
On execution the error code is -417
One way to solve this problem would be to rewrite the query as the following:
select * from tableName f where f.a_c = coalesce(aC, f.a_c)
The form of query above is likely to be accepted. In order to find out the exact reason of the error you get, it is necessary to trace the actual SQL statement passed to Db2.
Another option of solving the problem may be to add the CAST operator, which would define the data type of your parameter:
select * from tableName f where (cast(aC as integer) is null or f.a_c = aC)
This is suggested in the description of the error you get

JPA - subtract two date column

I have project using EJB3 + JPA(eclipselink) + Oracle database + glass-fish
everything work fine i can get any table from database
what I want is to execute this sql statement using JPQL
select de - sysdate as newde
from deinfo;
I try this code
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Read the existing entries and write to console
String qSelect = "SELECT d.de - CURRENT_Date as newde FROM Deinfo d ";
Query q = em.createQuery(qSelect);
but it's throw the error when create query
An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing [SELECT d.de - CURRENT_Date as newde FROM Deinfo d ].
[7, 19] The left expression is not an arithmetic expression.
why I can't subtract tow date using JPQL but I can use the same sql above inside Oracle sql command and work fine
I also try
select CURRENT_Date as newde
it's return the current date so no problem with command
it's just I can't use mathematics operation on date using JPQL

JPA Native query on Oracle database

I'm trying to do a native query on an Oracle database involve dates but I'm just not getting something.
I have a table with a number of rows in it and I know that the record with the oid=1234 has the latest updatetimeutc field, where updatetimeutc is a Date field. So I do the following:
Query query1 = entityManager.createNativeQuery("select updatetimeutc from TABLE where oid=1234");
List<Object[]> resultList = query1.getResultList();
Object[] os = resultList.get(0);
Date date = os[0];
Query query2 = entityManager.createNativeQuery("select oid, updatetimeutc from TABLE where updatetimeutc > :d");
query.setParameter("d", date);
resultList = query.getResultList();
At this point, I'm expecting the resultList.size() == 0, but that's not what's happening. I'm getting the same row returned to me as in query1.
Can someone explain why this is happening or what I'm doing wrong?
Thanks
The solution is to make sure you are using a version of Oracle's JDBC drivers that produce a java.sql.Timestamp for native queries that return DATE field.

Error in creating query in openbravo through hql

This question might have answer ... But not for openbravo with postgresql database.
I have openbravo 3.0 framework. In my window i have two date fields namely fromdate and todate. The requirement is i have to write a hql where clause to filter the records on the basis of current date.The date field is of timestamp without timezone.
Means fromdate < currentdate
and todate > currentdate .
I went through this link and wrote the hql where clause as
e.id in(select s.id from Tablename as s where s.fromdate < current_Date and s.todate>current_date)
when i open this window i get this error as
Exception when creating query select e from Tablename as e
where ( e.id in(select s.Tablename_ID from Tablename as s where s.fromdate < (current_date) and s.todate < (current_date)
however if i remove the current date conditions as
e.id in(select s.id from Tablename as s).. It is working fine.
Is it because of current_Date function ? .I tried even with now function .. but i get the same error.
!!! Got The Error.
There is a problem in the query i wrote , in the where clause i am selecting the id's which is not correct,hence when i gave the below query it was running correctly.
(Tablename.fromdate < currrent_date and TableName.todate>current_date) There was no problem with the current_date function.
I thought may be it would help some one!!!
Tip: If you want to write hql query correctly in openbravo , pls install the Hql query tool module that is available freely for community edition of openbravo.
Happy Coding

Resources