Hello I have entity and have createdAt filed specified like this:
#JsonIgnore
#Column(name = "created_at")
#Temporal(TemporalType.TIMESTAMP)
protected Date createdAt;
Every entity includes this field. Now I have complicated SQL query which calculates profit between dates. Query looks like this:
#Query("SELECT SUM(CASE WHEN t.outcome = true THEN - t.amount ELSE t.amount END) as income " +
"FROM Transaction t " +
"WHERE t.property = :property " +
"AND t.createdAt BETWEEN :dateFrom AND :dateTo")
Double getPropertyProfitBetweenDates(#Param("property")Property property, #Param("dateFrom")Date dateFrom, #Param("dateTo")Date dateTo);
The function that parses dates as I want looks like this:
Calendar start = Calendar.getInstance();
start.add(Calendar.MONTH, -i);
start.set(Calendar.DAY_OF_MONTH, 1);
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
Calendar end;
end = (Calendar) start.clone();
end.add(Calendar.MONTH, 1);
end.add(Calendar.DAY_OF_MONTH, -1);
Date dateFrom = start.getTime();
Date dateTo = end.getTime();
When I try to access data via repository I call method like this:
transactionService.getPropertyProfitBetweenDates(property, dateFrom, dateTo)
Every time I receive null, but when I mannualy run query in mysql workbench I get correct records. Could you please help me solving this problem out?
I fixed the problem using java.sql.Date
Related
I want to extract (year, month, dayOfMonth) from a timestamp field using HQL for comparison in a where clause.
Example:
Query hibernateQuery = session.createQuery("select sum(t.amount) from Transaction t " +
"where extract_date(t.timestampField) = :date");
hibernateQuery.setParameter("date", LocalDate.of(2018, 10, 11));
System.out.println( hibernateQuery.getSingleResult() );
So I am looking for a function like this pseudo function extract_date(t.timestampField) that I've used in example above.
This should work properly
Query hibernateQuery = session.createQuery("select sum(t.amount) from Transaction t " +
"where DATE(t.timestampField) = :date");
hibernateQuery.setParameter("date", new java.sql.Date.valueOf("2018-10-11"));
Note: the data type returned by DATE(...) function is java.sql.Date so if you are having a java.time.LocalDate it can be easily converted to java.sql.Date as follow:
LocalDate localDate = LocalDate.of(2018, 10, 11);
java.sql.Date sqlDate = java.sql.Date.valueOf(localDate);
It is discussed in the following Q/A.
https://stackoverflow.com/a/29168526/7972796
I am using Java 7 and fetching records for a week.For valid_from column I am subtracting -7 from current date below. The format of date in DB is 12-FEB-18. For valid_to column I am using sysdate. I am not getting correct valid_from date. Can anyone review this what is wrong here.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
Date startdate = ((DateFormat)formatter).parse(formatter.format(todate1));
System.out.println(todayWithZeroTime);
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM >"
+ startdate+ " and a.VALID_TO > sysdate";
How can I parse only Date here. Currently I am getting Tue Feb 13 00:00:00 GMT 2018. I want 13-FEB-18 which I can send as variable in where condition.
Please suggest
You are converting a Date to a String then back to a Date.
Then you are using this Date object in your query, so it's toString() method gets called and yields a String representation which is probably not the one you wanted.
Avoid the last conversion from String to Date and just use
String startdate = formatter.format(todate1);
Note that you also have to escape the date string with quotes :
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where "
+ "a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM > '"
+ startdate+ "' and a.VALID_TO > sysdate";
Also consider having a look at Java time API and at How to use PreparedStatement
I have an SQL table in my Android project, that has a KEY_DATE field in Date format.
KEY_DATE + " DATE,"
My table is populated from the java code (date in dd/mm/yy format).
So now I need to make several date-related queries and something isn't working.
I need to make selections from a table for today, this month and this year.
Here's what I tried:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
Date todayD = new Date();
dateFormat.format(todayD);
String today = dateFormat.format(todayD);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
dateFormat.format(firstDay);
String selectQuery = "SELECT * FROM " + TABLE_PAYMENTS + "WHERE "
+ KEY_DATE +" BETWEEN " + firstDay + " AND " + today;
The query returns empty even though there's a lot of data for that period.
I believe something is wrong with data formats here. Can you help me to solve this?
Thank you in advance.
You are not formatting firstD, so you only get from the first day of the month at the current time on;
You should either use single quotes around the dates in your queries or use prepared statements, otherwise your server will understand your dates as math operations;
When querying for date ranges, remember that if you don't specify an hour with your date SQL will by default take it as zero hour (0:00:00.0000). If you use "between startDate and today", you get only midnight of today. If you use "between startDate and tomorrow", you get midnight of tomorrow too. You should use "date >= startDate and date < tomorrow" to get the proper range.
When writing queries with dates, I always prefer to use ISO format for the date strings: yyyy-MM-dd.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date todayD = new Date();
cal.setTime(todayD);
cal.add(Calendar.DATE, 1);
Date tomorrowD = cal.getTime();
String today = dateFormat.format(tomorrowD);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstD = cal.getTime();
String firstDay = dateFormat.format(firstD);
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE KEY_DATE >= '" + firstDay + "' AND KEY_DATE < '" + today + "'";
The problem is with the date formats for the data present inside the database and the date formats that you are passing (strings) to the sql query.
It is not a good practice to pass dates as string parameters to the sql query, so I strongly suggest use preparedStatement as shown below:
Date todayD = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE BETWEEN ? AND ?" ;
//create preparedStatement here
preparedStatement.setDate(1, firstDay);
preparedStatement.setDate(2, todayD);
i tried to get the relevent id for the selected date in hibernate.but it returns 0 size list.but the date is exist in the data base.but i cant get the id for that date
transaction = session.beginTransaction();
Query query = session.createQuery(" FROM RoomRate WHERE currdate='" + date + "'");
List<RoomRate> list = (List<RoomRate>) query.list();
Have a look at these examples
http://www.mkyong.com/hibernate/hibernate-criteria-examples/
The key point being that the date needs to be formatted as in
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
and then you can query using
" where date >= '" + sdf.format(startDate) + "'"
BTW - why do you have a transaction and a commit on a select?
I'm trying to translate my sql query to JPA Criteria Builder which is used in project which I'm working on and I stuck on date operation (PostgreSQL 9.3), I have a bit in where clause:
...AND cl.due_date + '3 YEARS' <= '2016-01-01 10:27:16.473' and cl.due_date + '3 YEARS' >= '2008-01-01 10:27:16.473'....
The problem is that I'm not able to create a Predicate object for "due_date" + "3 YEARS".
Does anyone know how to manage to do that?
Thanks in advance
You need to add (or subtract) the 3 years in Java, not in the query:
Calendar dueDateCalPlus3Years = Calendar.getInstance();
dueDateCalPlus3Years.set(set(year, month, date, hourOfDay, minute, second);
dueDateCalPlus3Years.add(Calendar.YEAR, -3);
Date dueDatePlus3Years = dueDateCalPlus3Years.getTime();
Expression<Date> cl; // initialize it!
Predicate predicate = criteriaBuilder.greaterThanOrEqualTo(cl, dueDatePlus3Years);
To be more concise, you can use the interval mapping CriteriaBuilder#between(), and the query you have posted results in:
Date date1;
Date date2;
Predicate predicate = criteriaBuilder.not(criteriaBuilder.between(cl, date1, date2));