MySql 和 MyBatis datetime 小数秒

MySql and MyBatis datetime fractional seconds

我使用 mysql 5.6.14。首先我创建了

CREATE TABLE `TEST` (
  `id` tinyint(3) unsigned zerofill NOT NULL AUTO_INCREMENT,
  `dateTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

来自 mysql 文档

To define a column that includes a fractional seconds part, use the syntax type_name(fsp), where type_name is TIME, DATETIME, or TIMESTAMP, and fsp is the fractional seconds precision. For example:

CREATE TABLE t1 (t TIME(3), dt DATETIME(6));

The fsp value, if given, must be in the range 0 to 6. A value of 0 signifies that there is no fractional part. If omitted, the default precision is 0. (This differs from the standard SQL default of 6, for compatibility with previous MySQL versions.)

因为我没有定义 fsp 这意味着 fsp 为零 - 没有小数部分。

这是我的mybatis结果映射器:

 <resultMap id="readItemsRM" type="com.Foo">
        <id property="id" column="id"/>
        <result property="dateTime" column="dateTime"/>
  </resultMap>

这是我的 Foo class

class Foo{
 private String id;
 private String dateTime
 //getters+setters
}

这是我做foo.getDateTime()

的结果

2015-01-21 16:46:03.0

为什么会出现这个“.0”,如何避免?

.0 的原因是我们告诉 MySQL 没有小数部分。 将 java 变量指定为字符串,我们让 MyBatis 为该参数执行 getString() ,这就是 MySQL JDBC 驱动程序格式化值的方式。

相反,有必要将 Java 变量设置为 java.util.Date,并使用 SimpleDateFormatter 对其进行格式化。