[英]MongoDB No converter found capable of converting from type [java.lang.String] to type [java.time.LocalDateTime]
[英]No converter found capable of converting from type [java.time.LocalDateTime] to type [java.util.Date]
我在 Springboot 中使用 MongoDBTempalate 并尝试聚合数据基础 LocalDateTime,其中我收到此错误:org.springframework.core.convert.ConverterNotFoundException:找不到能够从类型 [java.time.LocalDateTime] 转换为类型 [java .util.Date]
我尝试添加自定义转换器但没有帮助,我添加的代码是:
`@Bean
public MongoCustomConversions customConversions(){
List<Converter<?,?>> converters = new ArrayList<>();
converters.add(DateToLocalDateTimeConverter.INSTANCE);
converters.add( LocalDateTimeToDateConverter.INSTANCE);
return new MongoCustomConversions(converters);
}
enum DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {
INSTANCE;
@Override
public LocalDateTime convert(Date source) {
return ofInstant(source.toInstant(), systemDefault());
}
}
enum LocalDateTimeToDateConverter implements Converter<LocalDateTime, Date> {
INSTANCE;
@Override
public Date convert(LocalDateTime source) {
return Date.from(source.toInstant(ZoneOffset.UTC));
}
}`
有人可以告诉我在创建转换器时哪里出错了,或者除了在代码中将 LocalDateTime 更改为 Date 之外还有其他选择吗,因为发生的次数非常多,重构可能需要花费大量时间和精力
您可以在您的实体或 DTO 上尝试此注释,它会自动格式化日期。
@Document(collection = "sample") 公共 class Foo{
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = 'yyyy-MM-dd HH:mm', locale = "en-PH") private Date createdAt;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.