Substract years from current_date in JPQL - java

I want to delete the rows which are older than 2 years. In SQL I do it like this:
DELETE FROM table WHERE creation_date < (current_date - interval '2 year');
Now I want to do the same for my JPA Repository in Java with the JPQL.
In JPQL I get an error because interval is not known and the "-"(minus) is not correct.
JPQL Query
#Query("DELETE FROM table t WHERE t.creation_date < (current_date - interval '2 year')")
I would appreciate any suggestion.

You can calculate the dateTime in the application, assuming you are using LocalDateTime for creation_date
LocalDateTime dateTime = LocalDateTime.now().minus(Period.ofYears(2));
and pass the parameter in JPQL
#Query("DELETE FROM table t WHERE t.creation_date < :dateTime")
void deleteByDateTime(LocalDateTime dateTime)

Related

Spring Data #Query - How to get current date + day

I would like to get records that have date_time column is in a week from now, in a month from now
I have a query like this
public interface BookingRepository extends JpaRepository<Booking, Long> {
#Query("SELECT b " +
"FROM BOOKING b " +
"WHERE b.date_time < NOW() + INTERVAL 7 DAY and b.date_time > NOW()")
List<Booking> getListBooking();
}
In MySQL, NOW() + INTERVAL 7 DAY is working but in JPA #Query, I don't know which function is correspond to it.
In this situation, I have to use dynamic query instead of native query. So I'd like to use dynamic query and face this problem.
Please help.
Thank you!
there is no date_add in JPA so you would have few options:
use native query https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#_native_queries
implement custom jpa function for date modifications
parametrize query
personally i would go with query parametrization as it is easier to test and maintain in the long-run.

Postgres Interval not working with native spring data JPA query

I have created a native query with interval. The query works fine when i hard code day in query:
#Query(value="select * from orders where created_date < clock_timestamp() - interval ' 5 days'",nativeQuery=true)
But when i provide data with #Param like this:
#Query(value="select * from orders where created_date < clock_timestamp() - interval :day 'days'",nativeQuery=true)
List<Order> getData(#Param("day") String day)
I got this error:
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at
or near "$1"
You can't provide a value for an interval like that. You need to multiple the parameter value with your interval base unit:
"select * from orders
where created_date < clock_timestamp() - (interval '1' day) * :days"
As you are dealing with days, you can simplify that to:
"select * from orders
where created_date < clock_timestamp() - :days"
Another option is the make_interval() function. You can pass multiple parameters for different units.
"select * from orders
where created_date < clock_timestamp() - make_interval(days => :days)"
The notation days => ... is a named parameter for a function call. If the variable represents hours, you could use make_interval(hours => ..)
One solution is provided in this entry Spring Boot Query annotation with nativeQuery doesn't work in Postgresql
Basically:
#Query(value="select * from orders where created_date < clock_timestamp() - ( :toTime )\\:\\:interval",nativeQuery=true)
'toTime' is a Param from your repository and could be days, hour, minute... etc(review interval doc in Postgres) #Param("toTime") String toTime

How to use date_format when using JPQL/JPA

I am doing Java EE with MySQL as database and implementing JPA on my codes.
I have no problem retrieving the data from MySQL Workbench but when I change my syntax to JPQL's it does not work.
For e.g. in MySQL - it works
SELECT date_format(s.date,'%Y, %m, %d') from Transactions s;
in JPQL - it does not
SELECT date_format(s.date,'%Y, %m, %d') from TransactionEntity s;
How do i modify to suit the JPA query?
Note:
in JPQL the following works
SELECT s.date from TransactionEntity s;
SQL function date_format is not part of JPQL, as any documentation would tell you, so don't see the point in just pushing SQL into JPQL and expecting it to work.
What you can do with JPA 2.1 is invoke it as follows
function("date_format", s.date, '%Y, %m, %d')
where function is a way to invoke any native SQL function. This clearly means you lose database independence because that function is not valid on all datastores.
Sql function is available in JPQL. My JPA version is 1.11.9. Sample group by day query:
#Query(value = "SELECT count(ac) as count, function('date_format', max(ac.subscriptionStartDate), '%Y, %m, %d') as date FROM MyTable ac " +
"WHERE ac.subscriptionStartDate BETWEEN :startDate AND :endDate GROUP BY function('date_format', ac.subscriptionStartDate, '%Y, %m, %d')")
public List<Map<String,Object>> findRegisteredCustomersHistory(#Param("startDate") Date startDate, #Param("endDate") Date endDate);
The result of the query is the list that records the number of records grouped by days in formatted form.
Sample rows:
count: 3, date: 2019, 09, 10
count: 1, date: 2019, 09, 11
for your question, try this in JPQL:
#Query(value = "SELECT function('date_format', s.date, '%Y, %m, %d') as date from Transactions s;")

JPQL Check greater than less than date today in #Query annotation

I want to check weather validTill date is greater than today using JPQL. I know that I can achieve this by following.
Query q = em.createQuery("select e from MyEntity e where e.validTill > :today ");
and pass the :today parameter. But this is not I wanted. I want to do this using #Query annotation in the CrudRepository in Spring.
This is my code segment in the CrudRepository
#Query("SELECT e FROM MyEntity e WHERE e.validFrom < TODAY")
Iterable<MyEntity> findAllValid();
I don't know what I should put at the place TODAY to get the today's date. Please help me.
I found it. it's like this..
#Query("SELECT e FROM MyEntity e WHERE e.validFrom < CURRENT_DATE")
Iterable<MyEntity> findAllValid();
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).

Delete item from database after X days

I am trying to make a Java Thread, this thread have to delete from an MySQL database all the records, older than 7 days.
In my table i have a column that contain the date like this: 2013-10-28 17:00:00 .
And to do this i want to use JDBI library. and my question here if any one could give me and example of the query that i have to write.
I think it should look like this:
h.execute("Delete from MyTable where date >= (dt.now.dayofmonth() -7)
h.execute("DELETE FROM MyTable WHERE NOW() >= ADDDATE(date, INTERVAL 7 DAY);");
Try this::
h.execute("Delete from MyTable where DATEDIFF(CURDATE(), dateCOLUMN)>7");
"delete from MyTable where date >= date_sub(now(), interval 7 day)"

Categories

Resources