Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate date don't save the milliseconds

I'm saving an entity in hibernate with a creation date

    @Id
    @Column(name = "dtcreation")
    @Type(type="timestamp")
    private Date creation;
and I put a new Date on this field:
    entity.setCreation(new Date());
    entityDao.persist(entity);
but when it is saved on the db the time don't contains the milliseconds, but put it a 0 if I try to update with a query the value of the milliseconds it works...someone can help me?

after the persist method i have a record with 01/06/2011 15:00:00.0 but if i made an UPDATE i can change the milliseconds, so the db supports it.. the database is informix

like image 508
rascio Avatar asked Jun 01 '11 12:06

rascio


1 Answers

This is consistent with the documented behavior of java.util.Date and java.sql.Timestamp

java.util.Date stores down to the second, and java.sql.Timestamp is a thin wrapper to accommodate the nanosecond value of a SQL timestamp value. If you read the note on the Timestamp javadoc, it clearly states this difference.

If you don't want to lose your second fractions, and don't want to investigate alternative date libraries (e.g. the aforementioned Joda Time) you'll need to make the field a java.sql.Timestamp, and use the milisecond value of the current date to construct the initial value

java.util.Date date = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
entity.setCreation(timestamp);
like image 83
Stevi Deter Avatar answered Nov 05 '22 02:11

Stevi Deter