Creating Query using Date parameters with Spring Jpa Repository - spring

I want to execute a query via JpaRepository that uses Date objects as parameters (java.util.Date). However, each time the method from the repository is called, it returns a null value. When I pass Integer values and work with id instead of Date I don't get any errors and the query is successfully executed.
This is my query:
#Query(value="SELECT sum(o.price) FROM Order o WHERE o.dateCreatedAt BETWEEN ?1 AND ?2")
Double getTotalMoneyEarned(Date beginDate, Date endDate)
I don't know if I'm missing something. In my Order model object, dateCreatedAt is a column of type Date.

Add this line at imports block
import org.springframework.data.repository.query.Param;
This should work :
#Query(value="SELECT sum(o.price) FROM Order o WHERE o.dateCreatedAt BETWEEN :beginDate AND :endDate")
Double getTotalMoneyEarned(#Param("beginDate") Date beginDate, #Param("endDate") Date endDate)

Related

How to use the query dynamically in spring boot repository using #Query?

How to use the below query dynamically in spring boot repository using
#Query(value="SELECT * FROM do_not_track WHERE (user_id=7 ) AND ('2022-06-25' BETWEEN from_date AND to_date) OR ('2022-06-30' BETWEEN from_date AND to_date)",nativeQuery = true)
SELECT * FROM do_not_track WHERE (user_id=7 ) AND ('2022-06-25' BETWEEN from_date AND to_date) OR ('2022-06-30' BETWEEN from_date AND to_date);
How to write the above query using jpa method?
I have used as given below but it's not working.
findByUser_userIdAndFromDateBetweenOrToDateBetween(Long userId, Date fromDate, Date toDate,
Date fromDate2, Date toDate2)
The #Query annotation allows you to 'bind' a SQL statement to a method and also allows you to include placeholders in your query.
To create such placeholder values, at first you want to annotate the arguments you pass to the repository method with #Param("someName"), where 'someName' is the name of the placeholder that will later be used in the query.
Inside the query you can reference to a specific parameter using :someName.
In the end your repository method and query could look something like this:
#Query("SELECT * FROM do_not_track WHERE (user_id = :userId) AND (date
BETWEEN :fromDate AND :toDate) AND (date BETWEEN :fromDate2 AND :toDate2)")
findByUser(#Param("userId") Long userId,
#Param("fromDate") Date fromDate,
#Param("toDate") Date toDate,
#Param("fromDate2") Date fromDate2,
#Param("toDate2") Date toDate2)

How can I write execute store procedure when update Entity using jpa Native Query?

Execute store procedure
Update A Table
Query is working Sql
#Query("UPDATE A SET A.No=(SELECT * FROM f_SP(tn,year,'name','1'))
,A.status=7 WHERE id=:id")
A saveObject(#Param("year") Integer year, #Param("tn") Long tn,
#Param("name") String name, #Param("id") Long id);
You may need to separate out the stored proc query and the update query at repository level like this :
#Procedure(procedureName = "f_SP")
Long reconcileEOMAndPIPSP(Long tn, String name, 'name','1');
#Query("UPDATE A SET A.No= :spResult ,A.status=7 WHERE id=:id")
A saveObject(#Param("spResult") Long spResult, #Param("id") Long id);
and wire then together at the calling class.

Passing Date to NamedParameterJdbcTemplate in Select query to oracle

I have a query as below which is returning expected records when run from the SQL Developer
SELECT *
FROM MY_TABLE WHERE ( CRT_TS > TO_DATE('25-Aug-2016 15:08:18', 'DD-MON-YYYY HH24:MI:SS')
or UPD_TS > TO_DATE('25-Aug-2016 15:08:18', 'DD-MON-YYYY HH24:MI:SS'));
I think that we will not need to apply TO_DATE when we are passing java.util.Date object as date parameters but the below code snippet is silently returning me 0 records.
My SQL query in Java class is as below:
SELECT *
FROM MY_TABLE WHERE ( CRT_TS > :lastSuccessfulReplicationTimeStamp1
or UPD_TS > :lastSuccessfulReplicationTimeStamp2);
The code which executes the above query is as below but the below code snippet is silently returning me 0 records:
parameters.put("lastSuccessfulReplicationTimeStamp1", new java.sql.Date(outputFileMetaData.getLastSuccessfulReplicationTimeStamp().getTime()));
parameters.put("lastSuccessfulReplicationTimeStamp2", new java.sql.Date(outputFileMetaData.getLastSuccessfulReplicationTimeStamp().getTime()));
list = namedParameterJdbcTemplateOracle.query(sql, parameters, myTabRowMapper);
Please advise.
I guess you already found the answer but if anybody else needs it, here's what I've found:
java.sql.Date doesn't have time, just the date fields. Either use java.sql.Timestamp or java.util.Date. Both seems to be working for me with NamedParameterJdbcTemplate.
A little variation to above solution can be when your input(lastSuccessfulReplicationTimeStamp1/lastSuccessfulReplicationTimeStamp2) is a String instead of Date/TimeStamp (which is what i was looking for and found at this link -> may be it can help someone):
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("lastSuccessfulReplicationTimeStamp1", lastSuccessfulReplicationTimeStamp1, Types.TIMESTAMP);
parameters.addValue("lastSuccessfulReplicationTimeStamp2", lastSuccessfulReplicationTimeStamp2, Types.TIMESTAMP);
list = namedParameterJdbcTemplateOracle.query(sql, parameters, myTabRowMapper);

How to run between and like clause while using Pagination and Sorting With Spring Data JPA

I have to execute a query which is
SELECT * FROM transaction WHERE account LIKE '%deepak%' and date_created BETWEEN 'Thu Jan 01 00:00:00 IST 2015' AND 'Wed Dec 16 00:00:00 IST 2015' ORDER BY date_created ASC OFFSET 5 LIMIT 10;
currently I am able to perform 4 functions using JPA which are:-
Set Offset
Set Page Size
Set Direction
Set Sort by column name
using the following code:-
PageRequest request = new PageRequest(1, 10, Sort.Direction.ASC, date_created );
return transactionRepository.findAll(request);
But how to perform remaining functions i.e. 'between' clause and 'like' clause using Pagination and Sorting With Spring Data JPA
Other suggested methods are also welcome.
Take a look at Spring jpa data reference documentation ,
Add this to your repository that extends PagingAndSortingRepository<..,..>
findByAccountLikeAndDateCreatedBetween(String account,Date start,Date end,Pageable pageable)
If you're familiar with JPQL you can always annotate a query with #Query inside your repository. ie:
#Query("select t from transaction t where t.name like ?1")
List<Transaction> getTransactions(String name, Pageable pageable)
where ?1 is the first parameter you passed, in this case name. Note that Pageable must always be the last parameter. This way you can name your query whatever you want.
See more info here.

Passing java.sql.Date to sql query

This is a part of my code
java.sql.Date d1=java.sql.Date.valueOf("2011-03-02");
java.sql.Date d2=java.sql.Date.valueOf("2011-03-10");
java.sql.Date systemDate=java.sql.Date.valueOf("2011-03-04");
String sql="select id from period where '"+systemDate+"' between '"+d1+"' and '"+d2+"'";
This is my code. I want to get the id which falls between these dates. But i am not getting the desired result. I am getting back all the id present in the table.
Do you have good results when you use other SQL tools (like pgadmin for PostgreSQL or SQL Developer for Oracle)?
Is so then try to use PreparedStatement. In your case this will look like:
PreparedStatement pstmt = con.prepareStatement("select id from period where ? between ? and ?");
pstmt.setDate(1, systemDate);
pstmt.setDate(2, d1);
pstmt.setDate(3, d2);
You're not using a field from your table to compare with your date range.
What you're doing is checking if 04-03-2011 is between 02-03-2011 and 10-03-2011, which is true for every record.
What you want to do is something like this (assuming start_date is a column in your table):
String sql="select id from period where start_date between '"+d1+"' and '"+d2+"'";
(Also, I agree with the answer above that prepared statements are a better way to construct queries.)

Resources