简体   繁体   中英

Rounding issues storing java.util.Date into MySQL datetime

MySQL DB column:

PLANNING_DATE datetime

Java field:

private java.util.Date planningDate;

Hibernate mapping:

<property name="planningDate" column="PLANNING_DATE" type="timestamp" not-null="true"/>

The problem: PLANNING_DATE in MySQL DB does not always match planningDate field. Sometimes, it gets an offset of 1 second. Is this a rounding issue?

Ok, I think it's because in MySQL >= 5.6.4 they changed DATETIME to truncate fractional seconds by default. I updated our table schemas to use the new DATETIME(6). I'll check if this was indeed the cause.

http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html

EDIT: Actually, DATETIME in MySQL >= 5.6.4 (which is equivalent to DATETIME(0)) rounds to seconds precision, as opposed to DATE in Oracle which truncates. Added a custom Hibernate type to do truncation instead of rounding and the problem was solved.

I don't know much about either MySql or Hibernate, but here goes…

A) You probably should be using java.sql.Date. It is a thin subclass of java.util.Date, meant fir use with JDBC.

B) The MySql doc do mention that their date-time types do not store the fractional part of a second. So perhaps there is rounding happening. But the docs mention truncation.

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