how to find difference between two timestamp using hibernate query language - java

I am trying to write an hql query which gives me the number of hours between two timestamp.
So, far i am unable to do this. I have used hql hour function but that does not work if the
timestamp corresponds to different date. Please provide any input.
My hql query is
select count(*) from com.xxx.Request as request where request.id = :id and hour(current_timestamp - request.lastEventDate) > :delay

well, you can use:
days(first_timestamp) * 24 + hours(first_timestamp)
- days(second_timestamp) * 24 - hours(second_timestamp);

Related

How to use Oracle TRUNC and NVL function together in JPA Predicate?

I have a specific Oracle query that has the following condition in where clause:
SELECT col_a
FROM table_x
WHERE TRUNC(NVL(date_col, sysdate + 365)) >
TRUNC(TO_DATE('11-Jan-2001', 'dd-mon-yyyy'));
I am unable to figure out how to use CriteriaBuilder to create the where clause Predicate. So far, I have figured out a half way but getting stuck at sysdate + 365 part. I specifically need to get DB date as my application current date and DB current date might differ.
Predicate p = criteriaBuilder.greaterThan(
criteriaBuilder.function("TRUNC", LocalDate.class, root.get(date_col)),
criteriaBuilder.function("NVL", LocalDate.class, root.get(date_col))
);
I'm unable to figure out how to get sysdate + 365 and pass it to criteriaBuiler.
Can anyone please help here? I can't post the complete snippet due to corporate restrictions.

how to write the sql queries to hibernate

id name date
1. ask 2018-04-25 12:30:59
2. msk 2018-04-25 12:40:43
3. sdf 2017-05-25 12:42:34
id=int---->in java id-->int
name=varchar(25)----> in java name-->string
date=datetime------->in java date--->Timestamp
my sql query=select * from table where year(date)='2018';
o/p:1. ask 2018-04-25 12:30:59
2. msk 2018-04-25 12:40:43
select * from table where month(date)='05'
o/p:3. sdf 2017-05-25 12:42:34
please help me i dont know
how to write this query in hibernate
How to write the above queries in hibernate? I have tried lot things but I didn't get any solution. If I use to_char() in hibernate it will give a unexpected token error.
You do not have to use to_char() function. Hibernate supports year and date functions.
Refer this link: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html
and look under "14.10. Expressions".
So your hql would simply look like this:
select t from table t where YEAR(t.date)='2018';
and select t from table t where MONTH(t.date)='05';
there is no need to use to_char() method here. you can simply use this query inside your Dao Implementation class.
for years:
session.createSQLQuery("select * from table where year(date) = :year")
.setParameter("year",2018)
.list();
for Months
session.createSQLQuery("select * from table where month(date) = :month")
.setParameter("month",05)
.list();

SQL Query into Hibernate takes infinite time

I am trying to execute an SQL query into Hibernate because of the complexity of it. To do so, I am using the following method:
session.createSQLQuery(sSql).list();
And the SQL query is:
String sSql = "select timestamp, value, space_name, dp_id, dp_description from "+sTable+
" inner join space_datapoint on id = dp_id and timestamp between "+
" (select max(timestamp)-30 day from "+sTable+") and (select max(timestamp) day from "+sTable+")"+
" order by space_name";
The SQL query tries to retrieve a set of values by means of cross references between multiple table/views. The result is a list of objects (different fields from the tables). I have tested the query in the SQL manager of the database and it works. However, when I run it inside the Hibernate framework, it takes a lot of time (I had to stopped the debugger after some minutes, whereas it should take over 5 seconds according to the tests). Do you know what could be the mistake? Or a possible solution?
Thanks a lot in advance,

Getting the totalworkingdays dates through passing the dates dynamically

This is my MySQL database table structure and attendancedate datatype is Date:
attendancedate-------admissionnumber------------attendance
2013-10-03-----------LSTM-0008/2013-2014--------present
2013-10-09-----------LSTM-0008/2013-2014--------present
2013-11-02-----------LSTM-0008/2013-2014--------absent
and i want to disaply like that
monthname---------totalworkingdays---------present----absent
october-------------- 2--------------------2----------0
November--------------1--------------------0-----------1
so am writing the below MySQL query:
select monthname(attendencedate) as monthname,
(select distinct count(*)
from lstms_attendence
where attendencedate>='2013-10-03'
and attendencedate<='2013-10-09'
and addmissionno='LSTM-0008/2013-2014')as totalworkingdays,
sum(CASE WHEN attendence = 'present' THEN 1 ELSE 0 END) as present,
SUM(CASE WHEN attendence = 'absent' THEN 1 ELSE 0 END) AS absent
FROM lstms_attendence
WHERE addmissionno='LSTM-0008/2013-2014' GROUP BY monthname(attendencedate);
But the query is display like this:
monthname---------totalworkingdays---------present----absent
November-----------3-----------------------0------------2
October------------3-----------------------2------------1
please give me the exact query and here am passing dates as hardcoded but that dates are passing dynamically through java to that query.
Let me know the how to create dynamically dates and how to pass values to that query.
Try this:
SELECT
MONTHNAME(attendencedate) as the_month,
COUNT(*) as working_days,
SUM(IF(attendance='present',1,0)) as is_present,
SUM(IF(attendance='absent',1,0)) as is_absent
FROM
lstms_attendence
WHERE
addmissionno='LSTM-0008/2013-2014'
GROUP BY
the_month
Your question doesn't make clear what you're asking. What's wrong with your resultset? Is it the presence of your "november" row?
At any rate, you've got an excessively complex query here, as well as one which will break if you happen to include data from multiple years in it.
Instead of using MONTHNAME(attendancedate), we'll use
DATE_FORMAT(attendancedate, '%Y-%c-01') AS attendancemonth
to figure out in which month an attendancedate lies. This simply turns '2013-11-15' into '2013-11-01', the first day of the month in question. In other words, it truncates (rounds down) the date to the first day of the month.
SELECT admissionnumber,
DATE_FORMAT(attendancedate, '%Y-%c-01') AS attendancemonth,
COUNT(*) AS working_days,
SUM(IF(attendance='present',1,0)) AS is_present,
SUM(IF(attendance='absent',1,0)) AS is_absent
FROM lstms_attendence
WHERE attendancedate >= '2013-10-03'
AND attendancedate < '2013-10-06' + INTERVAL 1 DAY
AND admissionnumber='LSTM-0008/2013-2014'
GROUP BY admissionnumber,attendancemonth
Here is a sqlfiddle.http://sqlfiddle.com/#!2/a2dfb/7/0
This summarizes by both admissionnumber and month, so you can produce a report that contains multiple admissions if you want that.
It uses attendancedate < 'last' + INTERVAL 1 DAY in place of attendancedate <= 'last' because that is robust in cases where attendancedate contains a timestamp other than midnight.
If you need to pass in your parameters from Java, use a prepared statement. Replace the constants in the SQL query with ?, and use setTimestamp and setString. For one example, see JDBC Prepared Statement . setDate(....) doesn't save the time, just the date.. How can I save the time as well?

Returning records from database between two dates

I've created a program using Java that connects to a database and allows the user to submit a record. This record includes a unique reference number and started date (Variable: StartedDate).
I want to enable the user to search for the amount of cases submitted between two dates (the first day of the month and todays date).
So far I have the SQL query
select * from cases where StartDate>'***' and Date<'****'
In Java, it would be
select * from cases where StartedDate>'1stMONTHDATE' and Date<'TODAYSDATE'
My first question is - Within the database, there isn't a field called "Date" as this would have to change on a daily basis. How would I reference this to be the automatically generated date from Java?
Also, how would I implement the Count() method to return an int of the number of records returned?
SELECT * FROM cases WHERE StartedDate BETWEEN :startDate AND :endDate
In JPQL:
public List<Cases> findAllEvents(Date startDate, Date endDate) {
List<Cases> allCases = entityManager.createQuery("SELECT * FROM cases WHERE StartedDate BETWEEN :startDate AND :endDate")
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
return allCases ;
}
Well i suppose by "Date" in the query you mean end date.
if that is so you can calculate the end date with either of the two following methods
java using the Calender class and pass the end date as parameter to the query
In the sql by modifying the query like
for ex- here the end date is one month from start date.This is DB specific.This will work in Postgres. Look for the correct syntax according to the DB you use to get the end date
select * from cases where StartedDate>'1stMONTHDATE' and ('StartedDate' + INTERVAL '1 MONTH')<'TODAYSDATE'.
Regarding the count()-A simple SELECT Count(*) will give you the number of rows returned by thw query
If you are using MSSQL and your date values are as String then you can use following query:
SELECT c FROM cases c where CONVERT(VARCHAR(10),StartDate,121) between :startDate AND :endDate
I am using this query in my application with mssql server

Categories