Why mybatis insert java.util.Date value to Mysql datetime column then fetch it they are not equal?

為{幸葍}努か 提交于 2019-12-12 03:18:42

问题


Mybatis insert java.util.Date to mysql datetime column, then fetch it find they are not match

Table

CREATE TABLE `t` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`create_time` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

code

@Insert("insert into t(create_time) values(#{0})")
int insertT(Date date);
@Select("select create_time from t order by id desc limit 1")
Date getLatestCreateTime();

Unit test

    Date date1 = new Date();
    mapper.insertT(date1);

    Date date2 = mapper.getLatestCreateTime();

    Assert.assertEquals(date1, date2);

Assert fail

java.lang.AssertionError: 
Expected :Tue Aug 02 22:10:35 CST 2016
Actual   :Tue Aug 02 22:10:36 CST 2016

why is so?


回答1:


because when TimeUtil in mysql-connector convert Timstamp to Date, it executes below code

    Timestamp ts = new Timestamp(tsAsMillis1 + (long)offsetDiff);
    ts.setNanos(secondsPart); 

and secondsPart is 0.

@Test
public void test_date_compare_date_from_timestamp() {
    Date date1 = new Date();

    Timestamp ts = new Timestamp(date1.getTime());
    System.out.println(ts);  // 2016-08-08 22:37:37.078
    Date date2 = new Date(ts.getTime());
    Assert.assertEquals(date1, date2);
    ts.setNanos(0);
    System.out.println(ts); // 2016-08-08 22:37:37.0
    Date date3 = new Date(ts.getTime());
    Assert.assertNotEquals(date1, date3);
}

and as for the seconds is more then original seconds, it is because

insert into t select 1,'2016-08-08 22:42:44.676';
select * from t;
+----+---------------------+
| id | create_time         |
+----+---------------------+
|  1 | 2016-08-08 22:42:45 |
+----+---------------------+


来源:https://stackoverflow.com/questions/38722942/why-mybatis-insert-java-util-date-value-to-mysql-datetime-column-then-fetch-it-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!