0

I have an class like this:

class Runner{ Date start; Date finish; }

and a table in oracle to store runners. My problem is when I set the day:

start = new Date(System.currentTimeMillis()); //I use java.util.Date

And when I use Hibernate to save object to DB. The time is always 00:00:00 (the day is correct). The column is DATE type. I debugged i found that be before save to db. start had right value. I have no idea about this.

Can you guy help me, please?

Update: I'm using Hibernate. my hbm file like:

<property name="startDate" type="date">
    <column name="START_DATE" length="7" />
</property>

The finish is the same. In hibernate, when save: I use session.save(entity).

But when I use query to update finish like

String updateQuery = "UPDATE Runner SET finish = ? WHERE id = ?"; then use setParameter to set finish datetime. It's OK.

4
  • 1
    "And when I use spring to save object to DB". You have to put this piece of code, problem lies there. Dec 27, 2013 at 12:40
  • 1
    I think you should parse your date do java.sql.Date before inserting it in the database, or use java.sql.Date instead. Are you using JPA, Hibernate, or JDBC? Dec 27, 2013 at 12:46
  • @edubriguenti that may solve this problem Dec 27, 2013 at 12:48
  • You have to use: start = new java.sql.Timestamp(System.currentTimeMillis()); and setTimestamp() on your PreparedStatement
    – user330315
    Dec 27, 2013 at 12:54

3 Answers 3

3

The Date class in JDBC stores only the date (as in just year and day). If you want to store also the time of the day you should use the Timestamp class, and the methods that go with it.

3
  • 5
    @dasblinkenlight: Joni is right. The JDBC class java.sql.Date only stores the date (the time part is removed - read the Javadocs). Don't confuse java.sql.Date with Oracle's DATE. Joni's advise to use java.sql.Timestamp for Oracle DATE columns is the correct answer.
    – user330315
    Dec 27, 2013 at 12:49
  • Except that he already uses java.util.Date, and the problem is how it's written to the database.
    – KarlP
    Dec 27, 2013 at 12:53
  • @KarlP: java.util.Date is not java.sql.Timestamp! (and setTimestamp() only makes sense when using a java.sql.Timestamp as you also correctly suggested.
    – user330315
    Dec 27, 2013 at 12:53
0

Since Oracles DATE type have a resolution of milliseconds, it's something in your java code that isn't right.

JPA? Use TemporalType to specify that it should be handled as a timestamp.

JDBC, use setTimestamp. (Perhaps setObject might work.)

0

Java data class only store the date if you want to store date with time you need to use java.sql.Timestamp, and in data database field must be datetime datatype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.