ZonedDateTime
和MongoDB
。我可以将ZonedDateTime
保存在MongoDB
中,但当我查看记录时,里面有很多不必要的东西。> "timestamp" : {
> "dateTime" : ISODate("2016-12-13T13:45:53.991Z"),
> "offset" : {
> "_id" : "-05:00",
> "totalSeconds" : -18000
> },
> "zone" : {
> "_class" : "java.time.ZoneRegion",
> "_id" : "America/New_York",
> "rules" : {
> "standardTransitions" : [
> NumberLong(-2717650800)
> ],
> "standardOffsets" : [
> {
> "_id" : "-04:56:02",
> "totalSeconds" : -17762
> },
> {
> "_id" : "-05:00",
> "totalSeconds" : -18000
> }
> ],
> "savingsInstantTransitions" : [
> NumberLong(-2717650800),
> NumberLong(-1633280400),
> NumberLong(-1615140000),
> NumberLong(-1601830800),
> NumberLong(-1583690400),
> NumberLong(-1570381200),
> and so on....
当我尝试检索相同的日期时,它给了我以下结果:
> org.springframework.data.mapping.model.MappingException: No property
> null found on entity class java.time.ZonedDateTime to bind constructor
> parameter to!
在使用 LocalDateTime
时,我没有遇到这个问题。第一个问题是:我们是否可以更改某些设置,以便只保留带有 ZonedDateTime
的 ISODate
?第二个问题是:是否有类似于 Jsr310JpaConverters
的东西适用于 mongodb
?
更新:参考以下问卷调查,我创建了自定义转换器并注册了它们,但问题仍然存在。 Spring Data MongoDB with Java 8 LocalDate MappingException
public class ZonedDateTimeToLocalDateTimeConverter implements Converter<ZonedDateTime, LocalDateTime> {
@Override
public LocalDateTime convert(ZonedDateTime source) {
return source == null ? null : LocalDateTime.ofInstant(source.toInstant(), ZoneId
.systemDefault());
}
}
而
public class LocalDateTimeToZonedDateTimeConverter implements Converter<LocalDateTime,
ZonedDateTime> {
@Override
public ZonedDateTime convert(LocalDateTime source) {
return source == null ? null : ZonedDateTime.of(source, ZoneId.systemDefault());
}
}
按以下方式进行注册:
@Bean
public CustomConversions customConversions(){
List<Converter<?,?>> converters = new ArrayList<Converter<?,?>>();
converters.add(new ZonedDateTimeToLocalDateTimeConverter());
converters.add(new LocalDateTimeToZonedDateTimeConverter());
return new CustomConversions(converters);
}
@Bean
public MongoTemplate getMongoTemplate() throws UnknownHostException {
MappingMongoConverter converter = new MappingMongoConverter(
new DefaultDbRefResolver(getMongoDbFactory()), new MongoMappingContext());
converter.setCustomConversions(customConversions());
converter.afterPropertiesSet();
return new MongoTemplate(getMongoDbFactory(), converter);
}
<artifactId>spring-data-mongodb</artifactId>
。在 JPA 的情况下,提到的转换器会执行转换,但是在这种情况下,我需要创建一个自定义转换器吗? - Gurkha