Vic*_*Vic 16 java spring spring-data spring-data-mongodb java-time
我有以下类要使用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;
...
}
Run Code Online (Sandbox Code Playgroud)
DateTimeFormat注释javadoc状态:
声明字段应格式化为日期时间.支持按样式模式,ISO日期时间模式或自定义格式模式字符串格式化.可以应用于java.util.Date,java.util.Calendar,java.long.Long,Joda-Time值类型; 从Spring 4和JDK 8开始,到JSR-310也是java.time类型.
我使用的是Spring 4.1.1和JDK 8,所以我希望它适用于Instant
.但是,这是实际存储的内容:
"timeCreated" : {
"seconds" : NumberLong(1416757496),
"nanos" : 503000000
}
Run Code Online (Sandbox Code Playgroud)
如果我从即时到日期编写和注册自定义转换器,就像在这个答案中解释的一样,那么它是有效的,但是我想避免这种情况,因为我确信必须有更好的方法.
在进一步挖掘Spring源代码之后,我发现了以下Jsr310DateTimeFormatAnnotationFormatterFactory
看起来很有希望的类:
使用JDK 8中的JSR-310 java.time包格式化使用DateTimeFormat注释注释的字段.
它的'源代码没有引用Instant
,但确实引用了OffsetTime和LocalTime.即便如此,当我在我的示例中将Instant更改为OffsetDateTime时,它仍然存储为复合对象而不是ISODate.
缺什么?
我认为问题在于你试图使用Instant
什么时间。从概念上讲,它是时间线的一个点,并不意味着格式化。
众所周知,Java 8 time API 是着眼于 joda-time 开发的(并且有 joda-time 开发人员的参与)。这是来自 joda-time 的评论Instant
:
应该使用 Instant 来表示时间点,而不考虑任何其他因素,例如时间顺序或时区。
这就是为什么从 3.0 版本开始 Spring 中就没有了org.joda.time.Instant
in的格式化可能性。JodaDateTimeFormatAnnotationFormatterFactory
而且它也没有实施Jsr310DateTimeFormatAnnotationFormatterFactory
因此,您应该使用自定义转换器或考虑使用更合适的类。
归档时间: |
|
查看次数: |
2870 次 |
最近记录: |