简体   繁体   中英

Storing Date in Hibernate with millisecond precision

I'm trying to persist a Date object in Hibernate with millisecond precision.

private Date date = new Date();

@Column(columnDefinition="DATETIME(3)")
public Date getDate() {
    return date;
}

But in the database the millisecond component is always .000. Is it simply not possible to store a Date object with millisecond precision using Hibernate?

java.util.date will only persist down to the second, since this is mapped to an SQL DATE type by the ORM, which may not contain milliseconds (at least in implementations I'm familiar with).

java.sql.timestamp supports fractional seconds.

I would definitely look into using the new Java 8 date libraries if you're able (or joda if you can't use Java 8). They're much better.

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

Try updating database connector version (.jar or dependency in case you use build automation tool). It worked for me. I used simple java.util.Date and DATETIME(3) in MySQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM