mapping dates in hibernate and mysql - java

We have an app in which we are using hibernate with mysql db.
We have a db script import.sql which have some insert into statements and we also have some date fields in db like start_date end_date in which we are string dates in default format, that is,YYYY-MM-DD.
Now issue is at the time of retrieving/comparing dates hibernates showing strange behaviour for example suppose if we have a date 2012-01-30 then hibernate reads in proper format that is, Jan 30 2012, but if we have a date like 2012-02-06 then hibernate reads as June 02 2012. my DAO for comparing and retrieving result is as follows
public final List<Record> getPastRecords(final java.util.Date currentDate) {
List<Record> pastRecord = session.createCriteria(Record.class)
.add(Restrictions.lt("endTime", currentDate))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return pastRecord;
}
Any idea what I am doing wrong?

without detailed code explanation guessing what may be the problem is very hard through i guess
it may be because of java.util.Date try to use java.sql.Date as when you call methods/constructors of libraries that deal with database better to use wrapper of java.util.Date which is java.sql.Date.
refer http://www.theresearchkitchen.com/archives/58

Related

Wrong date selection in SQL

I'm working with Hibernate 4.3.8.Final, Primefaces 6.0 and MySQL Database 5.7.13.
I have a table in the database with this structure:
CREATE TABLE `rents` (
`rent_code` INT NOT NULL AUTO_INCREMENT,
`rent_daystart` datetime default NULL,
`rent_dayend` datetime default NULL,
PRIMARY KEY (`rent_code`)
) ENGINE = innodb CHARACTER SET utf8 COLLATE utf8_unicode_ci;
And the following data extracted with Squirrel with the following SQL:
select * from rents
rent_code | rent_daystart | rent_dayend
1 | 2016-11-30 16:03:00.0 | 2016-12-01 16:03:00.0
In my Java bean I have the following function:
public List<Object> getRents(java.util.Date iniDate, java.util.Date endDate){
String SQL="select rent_code from rents where rent_daystart < :inidate and rent_dayend > :enddate";
List<Object> allRecords = null;
Session sesion=HibernateUtil.getSessionFactory().openSession();
try {
sesion.beginTransaction();
Query query = sesion.createSQLQuery(SQL).setDate("inidate", iniDate).setDate("enddate", endDate);
allRecords = query.list();
sesion.getTransaction().commit();
sesion.close();
}
catch (HibernateException he) {
//exception control code
};
return allRecords;
}
I execute the web APP debugging and the dates that the function receives are:
**inidate** = 'Wed Nov 30 17:54:00 CET 2016'
**enddate** = 'Wed Nov 30 18:54:00 CET 2016'
And it returns NO RECORD AT ALL.
If I execute the same SQL in squirrel that way:
select rent_code from rents where rent_daystart < '2016-11-30 17:54:00' and rent_dayend > '2016-11-30 18:54:00'
It returns one record.
I suspect that this is a data type problem or something like that, but after researching in the web it is not clear to me.
May someone help me?
Thanks in advance!
The java.util.Date class doesn't handle time zones. Unless you are using the same time zone in both your Date instance and the database fields, you can easily mismatch the time zones creating the behavior that you are seeing. Try and display the java Date in UTC format, and look at your database date in UTC format, and see if they line up like you expect.
If it is a date format mismatch between the values passed from the code and the values expected in database then use SimpleDateFormat to change the format of the date values before passing on to databse
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(iniDate);
Well, I have found the problem. As stated in Compare Date Java to DateTime Column in database table using SQL I was using the ".setDate" function to set the dates, such function truncates the time part, that was the problem. Now I'm using the ".setTimestamp" that uses both, date and time parts.
Thanks to all for your help, I have learned a lot about TimeZones!

How to select by date only if field is a timestamp?

I have a database field timestamp without timezone, that has values like 2015-11-23 14:42:55.278.
Now I want to find database records with just using the date part 2015-11-13.
Is that possible?
Ideally using hibernate and spring.
I'm not sure if is the best way in performace terms, but you may search dates between 2015-11-23 00:00:00.000 and 2015-11-23 23:59:59.999
If you want to fetch only for day 2015-11-13 then you can fetch all records using between keyword and by using timestamp of start of day.
dateField between 2015-11-13:<time_of_beginning_of_day> AND 2015-11-14:<time_of_beginning_of_next_day>
or
dateField between 2015-11-13:<time_of_beginning_of_day> AND 2015-11-13:<time_of_end_of_day>
You can cast the column to a date, e.g:
Postgres specific:
the_timestamp_column::date = date '2015-11-13'
or (standard SQL)
cast(the_timestamp_column as date) = date '2015-11-13'
You can also "reduce" the timestamp to different levels using date_trunc()
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC

Hibernate Envers Timestamp from revision date

I'm using MySQL and Hibernate Envers to log audity info, it saves a timestamp in a numeric format, how can i convert this timestamp to date in MySQL, not in Java?
Thanks!
UPDATE -
You can use FROM_UNIXTIME() in-built function.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime
Simply taking it into Date object, it should work -
Date date = resultSet.getTimestamp("timestamp");
I guess this timestamp includes milliseconds, so you can simply divide this value by 1000 :
FROM_UNIXTIME(hr.`TIMESTAMP`/1000)
Formatted:
DATE(FROM_UNIXTIME(hr.`TIMESTAMP`/1000))
OR
DATE_FORMAT(FROM_UNIXTIME(hr.`TIMESTAMP`/1000) ,'%Y-%m-%d %H:%i:%s')

java to format date and to return it as date object

I have a pojo class in which one of the field is date. Here I am using hibernate to insert values into the db using these pojos.
I have set the current date value for this property and I am inserting the value to the DB. Here I need to generate the insert script programaticaly. I have done this and i am printing the insert statement in the console. But while printing in the console the date is shown as Fri Jun 07 04:49:07 ACT 2013 and the insert statement is
INSERT INTO tables (dates)values('Fri Jun 07 04:49:07 ACT 2013');
I don't want to generate the script like this i need it as
INSERT INTO tables (dates)values('2013-06-07');
I know We can use simple date formatter but i need this as date to set the POJO value. So if it is String it will not be set into the object.
I am forming the query as below
StringBuffer columnName = new StringBuffer();
columnName.append("insert into Tables values ('"+obj.getdates()+"')");
Before i used logger and at that time the query was formed and i think hibernate took care of that formatting because after inserting the query was formed as
INSERT INTO tables (dates)values('2013-06-07');
But now by hardcoding it is giving the above query whcih is not getting executed as the date value is not correct.
Can anyone help me here. Also in the case of hibernate whether formatting is done by hibernate or at the backend whether it is converting automatically
Thanks
convert your date into java.sql.Date
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

Hibernate HQL and Date

I have a MySQL table with one of the column type as Date. In my hibernate mapping file I have mapped this column to type java.util.Date. Now in HQL while trying to retrieve objects based on date equality I do not get any results if I set the Date using new Date(). If I normalize the date by setting hours, minutes and seconds to zero I get results. Is this required since I have declared the SQL column type to be a Date and not Timestamp?
Try java.sql.Date
Hopefully this will help you out with the date equality issue.
RDJ
I was able to use java.util.Date with a SQL Server Date column by explicitly setting the #Type:
#Type(type="date")
public java.util.Date getDate() {
return date;
}
Without the annotation, I was getting
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
with Hibernate 3.5.1-final

Categories