简体   繁体   English

四舍五入问题将java.util.Date存储到MySQL日期时间

[英]Rounding issues storing java.util.Date into MySQL datetime

MySQL DB column: MySQL DB列:

PLANNING_DATE datetime

Java field: Java领域:

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. 问题:MySQL DB中的PLANNING_DATE并不总是与planningDate字段匹配。 Sometimes, it gets an offset of 1 second. 有时,它会偏移1秒。 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. 好的,我认为这是因为在MySQL> = 5.6.4中,他们更改了DATETIME来默认截断小数秒。 I updated our table schemas to use the new DATETIME(6). 我更新了表架构以使用新的DATETIME(6)。 I'll check if this was indeed the cause. 我将检查这是否确实是原因。

http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html 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. 编辑:实际上,MySQL中的DATETIME> = 5.6.4(等于DATETIME(0))四舍五入为秒精度,与Oracle中的DATE截断相反。 Added a custom Hibernate type to do truncation instead of rounding and the problem was solved. 添加了一个自定义的Hibernate类型来执行截断而不是舍入,从而解决了该问题。

I don't know much about either MySql or Hibernate, but here goes… 我对MySql或Hibernate都不了解,但是这里...

A) You probably should be using java.sql.Date. A)您可能应该使用java.sql.Date。 It is a thin subclass of java.util.Date, meant fir use with JDBC. 它是java.util.Date的一个瘦子类,意味着可以与JDBC一起使用。

B) The MySql doc do mention that their date-time types do not store the fractional part of a second. B) MySql文档确实提到它们的日期时间类型不存储秒的小数部分。 So perhaps there is rounding happening. 因此,也许正在四舍五入。 But the docs mention truncation. 但是文档中提到了截断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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