Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date Hibernate cut off time

I have a Date type column in Oracle DB and it contains date and time for sure. But when I'm trying to get data in java application it will return date with bunch of zeros instead of real time. In code it'll be like:

SQLQuery sqlQuery = session.createSQLQuery("SELECT table.id, table.date FROM table");
List<Object[]> resultArray = sqlQuery.list();
Date date = (Date)resultArray[1];

If it was 26-feb-2010 17:59:16 in DB I'll get 26-feb-2010 00:00:00 How to get it with time?

like image 591
Vlad Avatar asked Feb 26 '10 17:02

Vlad


People also ask

How do I remove the time from a Date object?

Use the toDateString() method to remove the time from a date, e.g. new Date(date. toDateString()) . The method returns only the date portion of a Date object, so passing the result to the Date() constructor would remove the time from the date.

Does Java Util Date store time?

No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java. util.

How do you truncate a Date in Java?

Use DateUtils. truncate() to throw out all fields less significant than the specified field. When a Date is truncated to the Calendar. MONTH field, DateUtils.


4 Answers

As others have already stated, you need to use java.sql.Timestamp to get the time.

However, if you use the @Temporal(TemporalType.TIMESTAMP) annotation on a Oracle's DATE column, Hibernate will complain and throw schema validation errors. To avoid those, add a columnDefinition like this:

@Temporal(TemporalType.TIMESTAMP)
@Column(name="EVENTTIME", columnDefinition="DATE")
private Date eventTime;
like image 160
Aerthel Avatar answered Sep 21 '22 10:09

Aerthel


I am not an expert with Oracle, but you probably need a DateTime column type to get a time stamp.

With that you need to use java.sql.Timestamp JDBC type.

like image 30
Alexander Pogrebnyak Avatar answered Sep 18 '22 10:09

Alexander Pogrebnyak


I had the same problem (Oracle Date type in the database).

The following mapping works for me:

<property name="timeStamp" type="java.util.Date">
    <column name="TIME_STAMP"/>
</property>
like image 22
hansfbaier Avatar answered Sep 19 '22 10:09

hansfbaier


I've encountered this issue in the past too. To resolve it, change your hibernate mapping from:

<property name="timeStamp" type="java.util.Date">
    <column name="TIME_STAMP"/>
</property>

to

<property name="timeStamp" type="timestamp">
    <column name="TIME_STAMP"/>
</property>

You can leave the data type in your Hibernate object as java.util.Date.

like image 30
Robert Durgin Avatar answered Sep 22 '22 10:09

Robert Durgin