rascio
rascio

Reputation: 9279

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

Upvotes: 5

Views: 13930

Answers (2)

Stevi Deter
Stevi Deter

Reputation: 1683

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

Upvotes: 10

Chad Wilson
Chad Wilson

Reputation: 121

Without your code to test it's difficult for me to definitively answer, but in taking a look at the Javadoc for java.sql.Timestamp, it appears that you're mixing types with annotating the field as a timestamp. Change the java type from Date to Timestamp and see if that solves your problem.

Upvotes: 0

Related Questions