我想使用 Spring Data 将以下类存储在 MongoDB 中
@Document()
public class Tuple2<T extends Enum<T>> {
@Id
private String id;
@Indexed
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private final Instant timeCreated;
...
}
DateTimeFormat 注释 javadoc 状态:
Declares that a field should be formatted as a date time. Supports formatting by style pattern, ISO date time pattern, or custom format pattern string. Can be applied to java.util.Date, java.util.Calendar, java.long.Long, Joda-Time value types; and as of Spring 4 and JDK 8, to JSR-310 java.time types too.
我使用的是 Spring 4.1.1 和 JDK 8,所以我希望它适用于 Instant
。但是,实际存储的内容如下:
"timeCreated" : {
"seconds" : NumberLong(1416757496),
"nanos" : 503000000
}
如果我按照 this answer 中的说明编写并注册从 Instant 到 Date 的自定义转换器然后它可以工作,但是我想避免这种情况,因为我确信必须有更好的方法。
在进一步挖掘 Spring 源代码后,我发现以下类 Jsr310DateTimeFormatAnnotationFormatterFactory
看起来很有希望:
Formats fields annotated with the DateTimeFormat annotation using the JSR-310 java.time package in JDK 8.
它的源不引用 Instant
,但它确实引用了 OffsetTime 和 LocalTime。即便如此,当我在示例中将 Instant 更改为 OffsetDateTime 时,它仍然存储为复合对象而不是 ISODate。
缺少什么?
最佳答案
我认为问题在于您尝试使用 Instant
作为时间。从概念上讲,它是时间线的一个点,并不意味着格式化。
我们知道,Java 8 time API 的开发着眼于 joda-time(并有 joda-time 的开发人员参与)。这是来自 joda-time Instant
的评论:
An Instant should be used to represent a point in time irrespective of any other factor, such as chronology or time zone.
这就是为什么 org.joda.time.Instant
在 JodaDateTimeFormatAnnotationFormatterFactory
中没有格式化可能性的原因,它从 3.0 版开始出现在 Spring 中。而且它也没有在 Jsr310DateTimeFormatAnnotationFormatterFactory
所以,你应该使用自定义转换器或考虑使用更合适的类。
关于java - 使用 SpringData-MongoDB 将 Java 8 Instant 存储为 BSON 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091418/