get relevent id for a date from the database - java

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?

Related

Java Spring JPA Repository between date query

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

How to fetch Records for a week

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

SQL statement in Java to sort by date (month)

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

How to convert a String to a Calendar object?

To store a Calendar object in SQLite database, i found that the easiest way is to convert the Calendar object to a string and store it in the database as text.
Now, the problem lies in extracting the stored date from the string.
How do I parse the string containing the Calendar object and set it to a Calendar value?
My code is:
String CREATE_DOCTORS_TABLE = "CREATE TABLE " + TABLE_DOCTORS + "("
+ KEY_ID_DOC + " INTEGER PRIMARY KEY," + KEY_DOCTOR_NAME + " TEXT,"
+ KEY_CLINIC_ADDRESS + " TEXT," + KEY_LAST_CHECKUP + " TEXT" + ");";
db.execSQL(CREATE_DOCTORS_TABLE);
where KEY_LAST_CHECKUP contains a value like this:
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=4,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=198,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=19,SECOND=47,MILLISECOND=823,ZONE_OFFSET=19800000,DST_OFFSET=0]
and i've stored it in a database this way:
values.put(KEY_LAST_CHECKUP, (doctor.getLastCheckUpDate().toString())); // last check up date
Now, how do i retrieve the DAY, MONTH and YEAR from the stored string?
I read about how to convert a date string to a calendar object here:
How to convert a date String to a Date or Calendar object?
but my string is not just a date string. It contains a lot of other details too.
What is the best way forward?
Change your data model to use a Date. This is the usual type to be stored in the database.
You can set the Date to a Calendar by using
Calendar c = Calendar.getInstance();
c.setTime(date);
To retrieve the Date from a Calendar you can use
date = c.getTime();
Using a String to store a Date in a database needs formatting and parsing of the Strings and also no comparision iside the database can be done.
If you would like to keep string value in KEY_LAST_CHECKUP column. Try to use SimpleDateFormat.
If you keep long value, you don't need to use SimpleDateFormat.
For insert :
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String strDate = simpleFormat.format(doctor.getLastCheckUpDate());
values.put(KEY_LAST_CHECKUP, strDate);
For retrieve:
try {
String strDate = --> from DB
Date parsedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(strDate);
Calendar c = Calendar.getInstance();
c.setTime(parsedDate);
} catch (ParseException e) {
return "Unknown";
}

Insert dd/mm/yyyy date format into database table

I am trying to insert a dd/mm/yyyy date format into my database table. The data type for date column in database is date and my SQL insert statement is:
INSERT INTO sm_product(productName, productDescription, productPrice, productQuantity, productStatus)
VALUES ('" + name + "', '" + desc + "', " + price + ", " + quantity + ", 'Available', '" + date + "'";
However, netbeans shows me an error when I added the date variable into the SQL statement.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
And it stores the date as:
Wed Jun 19 17:42:26 SGT 2013
And I got my dd/mm/yyyy date format in user interface:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
dateFormat.format(date);
This format is not I wanted. So I wonder how should I amend my SQL statement to fix the problem.
Thanks in advance.
If you are using SQL Server , you can use
REPLACE(CONVERT(VARCHAR(11),date,105),'-','/')
If you insert following format sting into query, record will be updated
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = new Date();
String formatDate = dateFormat.format(date);

Categories

Resources