Is there a way to use java LocalDateTime.now() in jpa #query? [duplicate] - jpa

I want to compare the date in database with current dateTime in JPA query :
captureLimitDate < currentDateTime
my requirement is as follows :
database.captureLimitDate : 04/07/2012 19:03:00
currentDateTime : 04/07/2012 20:03:00
My JPAQuery is this :
SELECT o FROM Operation o"
+ " WHERE ( o.merchantId =:merchantId ) AND "
+ "(o.captureLimitDate < currentDateTime ) ";
And Operation class has captureLimitDate as java.util.Date
#Generated(value = "XA", comments = "0,_8BedAMXZEeGHf_Dj4YaPyg")
private Date captureLimitDate;
I want to compare both current date and time . will the above query works. ??

CURRENT_TIMESTAMP must be used to refere to the current date and time in a JPQL query:
select o from Operation o
where o.merchantId = :merchantId
and o.captureLimitDate < CURRENT_TIMESTAMP
If the current date and time is in fact a date coming from user input (and which is thus not the current date and time, then you do it like you do for the merchantId:
select o from Operation o
where o.merchantId = :merchantId
and o.captureLimitDate < :maxDateTime
And you set the parameter using
query.setParameter("maxDateTime", maxDateTime, TemporalType.TIMESTAMP);

JPA defines special JPQL expressions that are evaluated to the date and time on the database server when the query is executed:
CURRENT_DATE - is evaluated to the current date (a java.sql.Date instance).
CURRENT_TIME - is evaluated to the current time (a java.sql.Time instance).
CURRENT_TIMESTAMP - is evaluated to the current timestamp, i.e. date and time
(a java.sql.Timestamp instance).
More info: Click here

Related

Create an inserted_at datetime where filter using simple date string

I'm trying to get records inserted after a certain date given to me by the client.
2018-06-06
Here's how I'm writing the query:
{:ok, date} = NaiveDateTime.from_iso8601(date_string)
from(
m in query,
where: m.inserted_at > ^date
)
(MatchError) no match of right hand side value: {:error, :invalid_format}
And when I try to use a simple Date object:
** (Ecto.Query.CastError) lib/messages/search.ex:77: value ~D[2018-06-06] in where cannot be cast to type :naive_datetime in query
How can I find all messages inserted after that dummy string date the client is passing me?
You have an ISO 8601 date there, not a datetime. You can convert it into a NaiveDateTime (with hour, minute, second all set to 0) like this:
iex(1)> date_string = "2018-06-06"
"2018-06-06"
iex(2)> ndt = NaiveDateTime.from_iso8601!(date_string <> " 00:00:00")
~N[2018-06-06 00:00:00]
Now you can use ndt in your query and it will work.

Query DateTime field using Date only in FileNet Content Engine

Is it possible to query using only a Date field such as '2017-03-02' in IBM FileNet?
I have tried the below statement and it doesn't seem to work
SELECT *
FROM Table_Name
WHERE EstimatedDate = '2017-03-02'
OR
SELECT *
FROM Table_Name
WHERE EstimatedDate <= DATE '2017-03-02'
I tried including TIMESTAMP and the below query works but i want to search only by using date such as '2017-03-02'
SELECT *
FROM Table_Name
WHERE EstimatedDate <= TIMESTAMP '2017-03-02T00:00:00.000Z'
To search for a particular date you need to use a range between two timestamps: start of the target day and start of the next day. For today's date the query will be:
SELECT *
FROM Table_Name
WHERE EstimatedDate >= 20180420T000000Z AND EstimatedDate < 20180421T000000Z
Please note that the timestamps above assume the UTC time zone (hence 000000Z). If your task is supposed to handle time zones, the timestamps should be adjusted accordingly. For example, for Europe/Rome (current time zone offset +02:00) that would be
EstimatedDate >= 20180419T220000Z AND EstimatedDate < 20180420T220000Z
According to IBM FileNet P8, Version 5.2
- SQL Syntax reference"
<literal> ::= <string_literal> | <integer> | <float> |
<ISO datetime> | <W3C datetime> | TRUE | FALSE | UNKNOWN | <guid>
<ISO datetime> ::= YYYYMMDDThhmmss[,ffff]Z
<W3C datetime> ::= YYYY-MM-DD[Thh:mm:ss[.ffff]][<timezone>]
Thus, in FileNet P8 do not use timestamp or date keywords, but only the date you have written in one of these formats, and note - without an apostrophe sign!
You can find examples in a free book Developing Applications
with IBM FileNet P8 APIs, for example on a page 73 there is Example 3-30 :
// Construct the sql statement
SearchSQL sql = new SearchSQL(
"select ISTOStartDate, ITSOEndDate, ITSOVehicle " +
"from ITSOIdleActivity " +
"where “ +
"ITSOVehicle = OBJECT('{D5DC8C04-2625-496f-A280-D791AFE87A73}') " +
"AND ITSOStartDate < 20090801T000000Z OR " +
"ITSOEndDate > 20090701T000000Z" );
As you see, the date in this example is written directly without any apostrophes as: 20090701T000000Z using <ISO datetime> format, you can also use another format: 2009-07-01

CrudRepository,Can't get the correct result query with And Between

I am having trouble using spring-boot CrudRepository,What I want to do is to look up the data for a period of time
I make a query by this and result is ok
List<T> findByTimestampAfter(#Param("timestamp") Date start)
This is also ok
List<T> findByTimestampBefore(#Param("timestamp") Date end)
But I tried the following three methods do not work:
List<T> findByTimestampBetween(#Param("timestamp") Date start,#Param("timestamp") Date end)
List<T> findByTimestampAfterAndTimestampBefore(#Param("timestamp") Date start,#Param("timestamp") Date end)
List<T> findByTimestampGreaterThanEqualAndTimestampLessThanEqual(#Param("timestamp") Date start,#Param("timestamp") Date end)
What I want to get is more than 100 data in the time frame, but there is only one which timestamp euqal end
And i try execute this sql statementselect:
select * from exchange where timestamp > "2018-01-02 17:30:00" AND timestamp < "2018-01-02 17:48:00";
i can see the more than 100 data.
I think I can not solve this problem
The keyword between is not supported inside method name. You should define your custom query, for example:
#Query("select * from exchange where timestamp > ?1 AND timestamp < ?2")
Object[] findByTimeCustomQuery(Date dFrom, Date dTo);
See the query executing from the jpa automatically.If you just use proper debugging logger .Also tell the proper result achieved from above three methods.

Postgresql Query very slow with ::date, ::time, and interval

I have a sql query that is very slow:
select number1 from mytable
where symbol = 25
and timeframe = 1
and date::date = '2008-02-05'
and date::time='10:40:00' + INTERVAL '30 minutes'
The goal is to return one value, and postgresql takes 1.7 seconds to return the desired value(always a single value). I need to execute hundreds of those queries for one task, so this gets extremely slow.
Executing the same query, but pointing to the time directly without using interval and ::date, ::time takes only 17ms:
select number1 from mytable
where symbol = 25
and timeframe = 1
and date = '2008-02-05 11:10:00'
I thought it would be faster if I would not use ::date and ::time, but when I execute a query like:
select number1 from mytable
where symbol = 25
and timeframe = 1
and date = '2008-02-05 10:40:00' + interval '30 minutes'
I get a sql error (22007). I've experimented with different variations but I couldn't get interval to work without using ::date and ::time. Date/Time Functions on postgresql.org didn't help me out.
The table got a multi column index on symbol, timeframe, date.
Is there a fast way to execute the query with adding time, or a working syntax with interval where I do not have to use ::date and ::time? Or do I need to have a special index when using queries like these?
Postgresql version is 9.2.
Edit:
The format of the table is:
date = timestamp with time zone,
symbol, timeframe = numeric.
Edit 2:
Using
select open from ohlc_dukascopy_bid
where symbol = 25
and timeframe = 1
and date = timestamp '2008-02-05 10:40:00' + interval '30' minute
Explain shows:
"Index Scan using mcbidindex on mytable (cost=0.00..116.03 rows=1 width=7)"
" Index Cond: ((symbol = 25) AND (timeframe = 1) AND (date = '2008-02-05 11:10:00'::timestamp without time zone))"
Time is now considerably faster: 86ms on first run.
The first version will not use a (regular) index on the column named date.
You didn't provide much information, but assuming the column named date has the datatype timestamp (and not date), then the following should work:
and date = timestamp '2008-02-05 10:40:00' + interval '30 minutes'
this should use an index on the column named date (but only if it is in fact a timestamp not a date). It is essentially the same as yours, the only difference is the explicit timestamp literal (although Postgres should understand '2008-02-05 10:40:00' as a timestamp literal as well).
You will need to run an explain to find out if it's using an index.
And please: change the name of that column. It's bad practise to use a reserved word as an identifier, and it's a really horrible name, which doesn't say anything about what kind of information is stored in the column. Is it the "start date", the "end date", the "due date", ...?

What type should you store the date in a database?

Currently I'm storing it as a String, but got problems using it when it comes to querying by date with GQL.
Date date = Calendar.getInstance().getTime();
DateFormat formatter = new SimpleDateFormat("hh:mm:ss, z");
String todayDate = formatter.format(date);
The query:
"SELECT FROM SomeTable p WHERE date = 01/01/2011"
Error:
Exception:
org.datanucleus.store.appengine.query.DatastoreQuery$UnsupportedDatastoreFeatureException:
Problem with query : Right side of expression is
composed of unsupported components.
Left:
org.datanucleus.query.expression.Literal,
Op: / , Right:
DyadicExpression{Literal{5} /
Literal{11}}
How can I search by date?
Always as a date - the database should check on the types of data that it stores thus making sure the data is what it says. the information about what type is known on the insert so check it then rather than later when none has any idea of what the correct value should have been.
the error you are getting is probably not due to this but because the date in the query needs to be made a date if types are correct or if a string needs to be as a single-quoted string see GQL Reference
e.g.
"SELECT FROM SomeTable p WHERE date = '01/01/2011'"
but what date is 06/07/2011 ? I think it is today 6th July, others 7th June. So even if you use strings use the ISO format 2011-07-06 A date type will hide this detail making it easier. Note that GQL only uses the ISO form so even if you got the command to have the date in a string it would fail.
but better as
SELECT FROM SomeTable p WHERE date = DATE( 2011, 1, 1)