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

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.

Related

#Query for selecting date from datetime

I have a JPA mapped "event" object that includes a timestamp column. I am trying to select all events that occurred on a specific date. To do this I need to ignore the time component of the timestamp. I am not sure that this is possible using non database specific functions? Something like this fails to select:
#Query("SELECT r FROM BioChemRequest r WHERE r.pasId = :pasid AND r.observationDate BETWEEN :startDate AND :startDate")
public List <BioChemRequest> find(#Param("pasid") String pasid , #Param("startDate") Date startDate);
try the following
#Query("SELECT r FROM BioChemRequest r WHERE r.pasId = :pasid AND r.observationDate BETWEEN :startDate AND :endDate")
public List <BioChemRequest> find(#Param("pasid") String pasid , #Param("startDate") Calendar startDate, #Param("endDate") Calendar endDate);
where startDate is a calendar with hour 00:00:00 000
and endDate is a calendar with hour 23:59:59 999

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.

How to compare date in a jpql query

Hi I want to list all the current records in my database where the date belong to the current month.
where d.jourvisite BETWEEN :startDate AND :endDate
this is my function
public List<Visite> getvisiteDétaillé() {
Calendar MyEnddate;
MyEnddate = Calendar.getInstance();
MyEnddate.add(Calendar.MONTH, 1);
TypedQuery<Visite> query;
query =
em.createQuery("SELECT v FROM Visite v JOIN v.datevisiteList d where d.jourvisite BETWEEN :startDate AND :endDate", Visite.class);
query.setParameter("startDate",Calendar.getInstance().getTime());
query.setParameter("endDate",MyEnddate,TemporalType.DATE);
System.out.println("date actual"+Calendar.getInstance().getTime());
System.out.println("date After 30 days"+MyEnddate.getTime());
return query.getResultList();
}
I'm sure that i have some records in the DB that are suitable for the query but when I display the result nothing to display with no syntax error
In the javadoc for TemporalType.DATE they mention:
Map as java.sql.Date.
but you are passing in a Calendar for endDate parameter.
Just pass in the Date instance like you do for the startDate parameter:
query.setParameter("endDate", MyEnddate.getTime());
PS You should follow the most used naming conventions to make the code more readable.

Entity Framework and date+time arithmetic

We have the situation where we have a SQL Server 2005 table with a Date column and a separate Time column. When I try to query this table, I'd like to do the equivalent of the following SQL:
where Date + Time > #Something
Some background info - the Date is stored as a date with a 00:00 time component, and the Time is stored as a Time with a 1900-01-01 date component - this means in SQL adding the two together get you a full DateTime.
I know there are indexing implications above, but that is not what the question is about.
How do you do this in linq to entities?
Some other things to note:
Changing the database schema is out of the question.
This is SQL 2005 so no Time datatype, and no TimeSpan returned from EF (I have tried changing the EF model to try and cast it to a TimeSpan, but no dice)
I want to try and stick to pure Linq-to-Entities and not go down the E-SQL / stored procedure / ExecuteQuery route.
Very lame idea, but:
var date = DateTime.Parse("2012-10-23");
var time = DateTime.Parse("1900-01-01 09:00:00);
var something = date + time;
[...] where Date + Time > something;
Entity Framework (versions > 4) has the EntityFunctions class. So you can do something like:
... where EntityFunctions.CreateDateTime(date.Year, date.Month, date.Day,
time.Hour, time.Minute, time.Second) < DateTime.Now
Or you could just do it the old fashioned way:
... where date.Date < DateTime.Now.Date || (date.Date == DateTime.Now.Date && time.Time < DateTime.Now)

SQL SERVER passing getdate() or string date not working correctly

CREATE PROCEDURE sp_ME
#ID int,
#ThisDate datetime = null
AS
SET NOCOUNT ON
IF #ThisDate IS NULL
BEGIN
SET #ThisDate = CURRENT_TIMESTAMP
END
DECLARE #intErrorCode int,
#QBegin datetime,
#QEnd datetime
SELECT #intErrorCode = ##ERROR
IF #ThisDate BETWEEN '01/01/' + CONVERT(VARCHAR(4), YEAR(#ThisDate))
AND '03/31/' + CONVERT(VARCHAR(4), YEAR(#ThisDate))
BEGIN
Select #QBegin = DATEADD(s,0,CAST ('10/01/' AS varchar(6) ) +
CONVERT(VARCHAR(4),DATEPART (year,#ThisDate)-1))
Select #QEnd = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#QBegin)+3,0))
SELECT * FROM QUERY
WHERE MEID = #ID
AND mydate >= #QBegin
AND mydate <= #QEnd)
END
SELECT #intErrorCode = ##ERROR
IF (#intErrorCode <> 0) GOTO ErrHandler
ErrHandler:
RETURN #intErrorCode
GO
It returns a dataset when you leave it blank and it assumes and fills in the date, however when you plug in a date it just states "The command completed successfully."
Any help would be more than appreciated.
At a guess, you need to query the previous quarter's results, which would just be this query:
SELECT * FROM QUERY
WHERE MEID = #ID
AND mydate >= DATEADD(quarter,DATEDIFF(quarter,'20010101',#ThisDate),'20001001'),
AND mydate < DATEADD(quarter,DATEDIFF(quarter,'20010101',#ThisDate),'20010101'))
And get rid of that big if condition, etc.
You could also get rid of the first if, if you put COALESCE(#ThisDate,CURRENT_TIMESTAMP) in the above, where I currently have #ThisDate.
I use the DATEADD(quarter,DATEDIFF(quarter,'20010101',#ThisDate),'20001001') pattern for a lot of datetime manipulation. It let's you achieve a lot in a few operations. In this case, it's the difference between the two dates ('20010101','20001001') which is giving us the previous quarter.
You'll frequently encounter the DATEADD/DATEDIFF pattern in questions involving removing the time portion from a datetime value. The canonical version of this is DATEADD(day,DATEDIFF(day,0,#Date),0). But the pattern can be generally extended to work with any of the datetime components. If you choose month rather than day, you'll get midnight at the start of the first of the month (of the day you've supplied)
Where it gets tricky is when you use dates (instead of 0), and especially if you don't use the same date for both calculations. This allows you to apply an additional offset that seems almost "free" - you're already using this construct to remove the time component, the fact that you can compute e.g. the last date in a quarter/month/etc is a bonus.