Spring JPA - JPQL Named Query Find All By Year And And month - java

I am trying to get all objects by specific month and year.
I have done this with Native Query
#Query(value = "select * from transaction_log as t where year(t.insurance_period)=(:year) AND user_id =(:userId) AND t.employer_id is null", nativeQuery = true)
And I want to be done with another way so I can use entity graphs etc.
I have try
#Query("select t from Transaction t where year(t.insuranceDate) = ?1 and month(t.insuranceDate) = ?2")
And I get error on method Year () for unexcepted '('
and the following with the same error at EXTRACT method.
#Query("SELECT t FROM Transaction t WHERE EXTRACT (YEAR FROM t.insuranceDate) = :year AND EXTRACT (month FROMt.insuranceDate) = :month")

You could use BETWEEN first day of month and last day of month. According to jpql doc BETWEEN is inclusive.
The downside is doing some date calculations, but they are trivial with java.time classes. Let's say you want dates from February 2020. You could get first and last day like this:
int year = 2020;
int month = 2;
LocalDate firstDay = LocalDate.of(year, month, 1);
LocalDate lastDay = firstDay.withDayOfMonth(firstDay.lengthOfMonth());
Then the query will look like this:
#Query("SELECT t FROM Transaction t WHERE t.insuranceDate BETWEEN :firstDay AND :lastDay")

Related

JPA Criteria add one day to the selected date

I have a JPA criteria that selects the max date from a table and I want to select the following day, e.g. if the query result is 1/20/17 I want the result to be 1/21/17
Here is my code:
CriteriaQuery<Date> maxDateCriteriaQuery = criteriaBuilder.createQuery(Date.class);
Root<DatesClass> datesClassRoot = maxDateCriteriaQuery.from(DatesClass.class);
maxDateCriteriaQuery.select(criteriaBuilder.greatest(datesClassRoot));
TypedQuery<Date> maxDateTypedQuery = entityManager.createQuery(amortizationsQuery);
Date maxDate = maxDateTypedQuery.getSingleResult();
I want to change the criteria to return the max date + 1
In oracle I will do it:
SELECT MAX(MY_DATE) + 1 FROM DATES_TABLE;
I will appreciate any help!
I assume you want to keep the original Date object in the database?
Than I would add 1 day to the day you retrieved from your DB:
Calendar c = Calendar.getInstance();
c.setTime(maxDate);
c.add(Calendar.DATE, 1);
Date newMaxDate = c.getTime();

compare existing month and year only in database after chosing date in java date picker

After chosing the date in date picker in java,i've got this format dd/mm/yyyy.But before inserting it in Oracle database i want first to compare only if month and year exist,not the day.If the month and year is already recorded i don't insert, if not,i insert it and reset the only the day to the first day of the month,but keep the month and year as they are.My program is only concerned by date and month,that why i want to know how to compare only the two before inserting.I've tried to do the following code:
Resultset res = st.executeQuery("select count(*) as rowCont from doc_arriv where month_arv=to_char(chosen_date,'mm/YYYY');
res.next();
But it isn't comparing
calendar=java.util.Calendar.getInstance();
calendar.setTime(chosen_date);
//we must add 1 here beacause Calendar intialise months by zero
int month= calendar.get(Calendar.MONTH)+1;
//we get the year
int year= calendar.get(Calendar.YEAR);
String req = "SELECT count(*) from doc_arriv where
EXTRACT(month FROM month_arv) = " + month +
"and EXTRACT(year FROM month_arv)= " = year ;
Resultset res=st.executeQuery(req);
res.next();
//continue your code here you must calculate the result of the request if more than 1 you insert else you dont insert and for change the day to the first day of month you must execute the code
calendar.set(Calendar.DAY_OF_MONTH, 1);
chosen_date= calendar.getTime();
//good luck
First of all better use a PreparedStatement. Then simply compare the dates of the with the first day of the month and the first day of the next month (assuming the type of the month_arv column is DATE):
LocalDate date = ...
LocalDate startOfMonth = date.withDayOfMonth(1);
LocalDate startOfNextMonth = startOfMonth.plusMonths(1);
// save for later use (insertion)
Date sqlStartOfMonth = Date.valueOf(startOfMonth);
PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM doc_arriv WHERE month_arv >= ? AND month_arv < ?");
statement.setDate(1, sqlStartOfMonth);
statement.setDate(2, Date.valueOf(startOfNextMonth));
ResultSet res = startment.executeQuery();

how to compare a given date with current date in sql

i want to write a query to compare a given date with today date with timestamp.
given date can be the today date, if the date is same it will compare the time.
select * from abcTable where submitDate <= now();
here its comparing only the date not the time.
submitDate is anydate which is in the db table.
Firstly, you have specified that column submitDate is of datatype Date while, as per your question its datatype should be Timestamp.When the datatype of submitDate column is Date, there is no reason to even compare the time.
However if you need to still want to compare the submitDate with current timestamp, you can do it this way:
select * from submitDate where date_format(submitDate,'%d/%m/%y %T') <= now();
Edit: The above query is for Mysql
I think you should try:
GETDATE() --2017-01-17 08:19:28.403
you can get day, month and year separately by doing:
select DAY(getdate()) --17
select month(getdate()) --1
select year(getdate()) --2017
if you are on sql server 2008, there is the DATE date time which has only the date part, not the time:
select cast (GETDATE() as DATE) --2017-01-17
OR you you can try:
select * from abcTable where submitDate <= CAST(CURRENT_TIMESTAMP AS DATE);
OR
select * from abcTable where submitDate <= cast((now()) as date);

How to get datetime difference in a day with joda time in java

Am trying to get datetime difference with joda time (ie startdate -2014-02-26 and enddate-2014-02-26) for a day but i keep on getting a blank table.When i change to startdate -2014-02-26 and enddate-2014-02-27 data gets displayed. below is sample code
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date todaydate = new Date();
DateTime jodaToday = new DateTime(todaydate);
String datefrom = sdf.format(jodaToday.toDate());
String dateto = sdf.format(jodaToday.plusDays(1).toDate());
and my query looks like below.
ProductTable.setContainerDataSource(storeData(
"SELECT * FROM sales where sale_time BETWEEN '"
+ datefrom + "' AND '" + dateto + " ' ORDER BY sale_time DESC"
));
What could i be missing ?
NOTE: When i do a test with the below query i get data
SELECT * FROM sales WHERE sale_time BETWEEN
'2014-02-26 00:00:00' AND '2014-02-26 23:59:59' ORDER BY sale_time DESC;
Thanks
Your problem is more about understanding the BETWEEN SQL statement. In simple words, BETWEEN can be explained as:
FOO BETWEEN A AND B
Which is equivalent to
FOO >= A AND FOO <= B
With this in mind, if you have sale_time >= '2014-02-26' AND sale_time <= '2014-02-26', it will be understood by your database engine as sale_time >= '2014-02-26 00:00:00' AND sale_time <= '2014-02-26 00:00:00'. So, the database engine won't be able to find a row which sale_time value is '2014-02-26 05:32:16' or similar.
After understanding this, then you're able to understand why setting the second parameter of your between works when you add one day to today. The SQL statement would be:
sale_time BETWEEN '2014-02-26' AND '2014-02-27'
Which can be understood as:
sale_time >= '2014-02-26 00:00:00' AND sale_time <= '2014-02-27 00:00:00'
I don't know vaadin but you should use a method where you will send these Strings as parameters rather than concatenating them to generate the query to execute. Note that if you do this more and more your application is prone to SQL Injection.
Data from midnight to midnight:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateTime from = new DateTime(2014, 2, 26, 0, 0).withTimeAtStartOfDay();
DateTime to = from.plusDays(1).withTimeAtStartOfDay().minusSeconds(1);
String datefrom = sdf.format(from.toDate());
String dateto = sdf.format(to.toDate());
EDIT
Maybe the extra space is the problem:
...dateto + " ' ORDER BY...
^
Little bit difficult to give an answer without the Table and data,
Set break point to the "datefrom" and check whether correctly set "datefrom" and "dateto".
Check the Table column DATE or TIMESTAMP.
Check data is available in table match your criteria.
Get this query and set hard-coded "datefrom" and "dateto" and execute as a SQL query in your DBMS.
The below is the solution that worked. Note added timestamp(23:59:59) in bold.
" AND sale_time >= '"+sdf.format(fromdate.getValue())+"' AND sale_time <= '"+sdf.format(Todate.getValue())**+" 23:59:59'"**;

Hibernate Criteria: NOW() < date + 1 day

I have a table in a MySQL DB with a date(DATETIME) column on it. How do I express it in java Hibernate criteria if let's say I would like to query for records where NOW() < ('date' + 1 day) ?
You could turn it the other way around and compare 'date' >= (NOW - 1 day).
Assuming you've got a mapped MyTable class with the date property:
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
Criteria criteria = session.createCriteria(MyTable.class);
criteria.add(Restrictions.ge("date", c.getTime());
List results = criteria.list();

Categories