TIMESTAMP in NamedNativeQuery using Spring Data JPA - oracle

The scenario is to fetch values from OracleDB where one of the search input is DateTime in the format "07/11/2017 10:12:16 AM" (which is a string) and the DB Column is TIMESTAMP.
The Data in the column is saved in the format "07/11/2017 10:12:16 AM" but it is a TIMESTAMP.
while querying from the Oracle DB, it is possible to convert the search input to the appropriate TIMESTAMP using TO_TIMESTAMP function
Example
select * from Table where SI_ID='12345'and COLUMN >= TO_TIMESTAMP ('07/11/2017 10:12:16 AM', 'mm/DD/YYYY HH:MI:SS AM';
I need to achieve the same in Java using Spring Data JPA and NamedQuery.
The NativeNamedQuery is called from the JPA repository is as follows
#Query(name = "Sample.findRecordByIdAndTime", nativeQuery = true)
Sample findByIdAndTime (#Param("id") Long id, #Param("timestamp") String timestamp);
But how to convert the string to TIMESTAMP in the Named query called from JPA repository which is given below:
#NamedNativeQuery(name="Sample.findRecordByIdAndTime", query="select * from TABLE where SI_ID= ? and TS_COLUMN >= TO_TIMESTAMP(?, 'mm/DD/YYYY HH:MI:SS AM')", resultClass = Sample.class)
Any help will be appreciated.

your query should work (as it native query), just add bind params : :id and :timestamp
#NamedNativeQuery(name="Sample.findRecordByIdAndTime",
query="select * from TABLE where SI_ID= :id
and TS_COLUMN >= TO_TIMESTAMP(:timestamp , 'mm/DD/YYYY HH:MI:SS AM')",
resultClass = Sample.class)

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 to convert Month-Year to date in HQL/Grails?

This query is working in database
select to_date(a.year || a.month, 'YYYYMM') as dates from table a
but not working in Grails as HQL. Giving an error as "unexpected token".
How do I use this query in HQL/Grails?
As example I have month & year column. I need to show this as date in new column.
Above to_date(a.year || a.month, 'YYYYMM') as dates works fine in oracle database but it doesn't work in HQL in grails where I'm using as
executeQuery("select to_date(a.year || a.month, 'YYYYMM') as dates from table a") but this one is not working
HQL is only good if you have modeled your database table. If you really want to use this exact query, go for native SQL instead of HQL:
MyController {
Sql groovySql // package: groovy.sql
def myAction() {
def results = groovySql.rows("SELECT 'thisIsNativeSqlQuery'");
// do something with your results;
}
}
If you have modeled this table already (has Domain class) you can just fetch them all with YourDomain.list() and make a getter method that forms your date from the format you have:
Date toDate() {
​ return Date.parse("yyyyMM", "201808")​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
}
or have transient field that does this for you, it all depends on your use case

Creating Query using Date parameters with Spring Jpa Repository

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)

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);

Extract year form date mysql

I am using spring-data-jpa, i want to extract year from date.
#Query("select t from Table t where extract(year from t.date) =: date")
Set<Table> extractYear(#Param("date") Integer date);
But it gives me an error
Using named parameters for method public abstract java.util.Set com.repositroy.extratYear(java.lang.Integer) but parameter 'date' not found in annotated query 'select t from Table t where extract(year from t.date) =: date'!
Remove the space between ":" and the parameter:
... "where extract(year from rec.closingDate) = :closingDate"

Resources