Java 8 日期/时间 (JSR-310) 类型与 Spring Data MongoDB 的映射

我有一个带有 Java 8 日期/时间字段的简单文档

I have simple document with Java 8 date/time fields

@Document
public class Token {
    private Instant createdAt;
    ...
}

我想坚持使用 Spring Data MongoDB 1.5 版.但是 java.time.Instant 类型的字段无法正确反序列化,因为 MappingMongoConverter 缺少 java.time 类的转换器.

that I want to persist with Spring Data MongoDB version 1.5. But fields of type java.time.Instant could not be de-serialized correctly because MappingMongoConverter lacks converters for java.time classes.

在 Spring 4 中,我发现 org.springframework.format.datetime.standard.DateTimeConverters 具有不同的 Converter,包括 InstantToLongConverterLongToInstantConverter 声明为私有静态类.

In Spring 4 I found org.springframework.format.datetime.standard.DateTimeConverters with different Converters including InstantToLongConverter and LongToInstantConverter declared as private static classes.

如何配置 MongoTemplate 以使用它们将 Instant 字段映射到 long?

How can I configure MongoTemplate to use them to map Instant fields to longs?

推荐答案

我不知道这是否是最好的方法,但我在 Spring Data MongoDB 中添加了 Java 8 Date/Time (JSR-310) 类型支持 1.5.0.RELEASE 像这样:

I don't know if this is the best way but I added Java 8 Date/Time (JSR-310) types support to Spring Data MongoDB 1.5.0.RELEASE like this:

  1. 第一步.添加简单的 Spring Converters

public class InstantToLongConverter implements Converter<Instant, Long> {
    @Override
    public Long convert(Instant instant) {
        return instant.toEpochMilli();
    }
}

public class LongToInstantConverter implements Converter<Long, Instant> {
    @Override
    public Instant convert(Long source) {
        return Instant.ofEpochMilli(source);
    }
}

public class LocalDateToStringConverter implements Converter<LocalDate, String> {
    @Override
    public String convert(LocalDate localDate) {
        return localDate.toString();
    }
}

public class StringToLocalDateConverter implements Converter<String, LocalDate> {
    @Override
    public LocalDate convert(String source) {
        return LocalDate.parse(source);
    }
}

  • 第二步.在 AbstractMongoConfiguration 实现中使用 MappingMongoConverter 注册这些自定义 Converter,如下所示:

  • Second step. Register these custom Converters with MappingMongoConverter in your AbstractMongoConfiguration implementation like this:

    @Configuration
    @EnableMongoRepositories(basePackages = {"my.app.repository"})
    public class MongoConfiguration extends AbstractMongoConfiguration {
    
        ...
    
        @Override
        public CustomConversions customConversions() {
            return new CustomConversions(Arrays.asList(
                    new InstantToLongConverter(), new LongToInstantConverter(),
                    new LocalDateToStringConverter(), new StringToLocalDateConverter()));
        }
    }
    

  • 现在您的文档的 Instant 字段将作为长值和 LocalDates 作为字符串持久化.

    Now your document's Instant fields will be persisted as long values and LocalDates as Strings.

    相关文章