Extract year form date mysql - spring

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"

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

TIMESTAMP in NamedNativeQuery using Spring Data JPA

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)

How to pass all in between dates from date range in "IN" operator for Oracle Pivot?

What I want is to pass a complete range of dates in the Pivot "IN" clause. But what i am doing is that using the values only that i am getting from database.
For ex.
Suppose if user select the From date as '10/10/2015' and To date as '10/15/2015' then I want to use all the values (10/10/2015,10/11/2015,10/12/2015,10/13/2015,10/14/2015,10/15/2015)
But what is happening from my query is ('10/10/2015','10/15'2015').
SELECT * FROM
(
SELECT
Employee.M_NAME AS MANAGER_NAME,
Employee.PHONE,
Employee.JOB_ID,
Employee.Assigned_DATE,
Employee.SHIFT,
Employee.Dept as Assignment,
Employee.E_ID,
Employee.NAME AS EMP_NAME,
Employee.DEPT_COLOR
FROM Employee
WHERE Assigned_Date BETWEEN
TO_DATE('FD_Selected','MM/DD/YYYY') AND
TO_DATE('TD_Selected','MM/DD/YYYY')
ORDER by Employee.E_ID
) x
PIVOT
(
min(Assignment)
FOR Assigned_Date IN (TO_DATE('FD_Selected','YYYY-MM-DD'),
TO_DATE('TD_Selected','YYYY-MM-DD')
)
) p
Now the data is coming like this:
M_NAME PHONE JOB_ID Assigned_DATE SHIFT Assignment E_ID EMP_NAME DEPT_COLOR '10/10/2015' '10/15/2015'
But I want like this:
M_NAME PHONE JOB_ID Assigned_DATE SHIFT Assignment E_ID EMP_NAME DEPT_COLOR '10/10/2015' '10/11/2015' '10/12/2015' '10/13/2015' '10/14/2015' '10/15/2015'

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

Resources