gpt4 book ai didi

java - 存储在 mongodb 上的 YearMonth 字段无法解析回对象字段

转载 作者:行者123 更新时间:2023-11-30 07:19:30 26 4
gpt4 key购买 nike

背景:我的应用程序构建在 Spring Data RESTMongoDB 存储库之上。

考虑这个带有 YearMonth 字段的简单 Java 域对象:

@Getter @Setter
public class Console {
@Id private String id;
private String name;
private YearMonth releaseMonth;
private Vendor vendor;
}

并且该域对象可通过 MongoRepository 实现进行持久化:

public interface ConsoleRepository extends MongoRepository<Console, String> {
Console findByName(@Param("name") String name);
}

当公开 REST Controller (由 Data REST 自动)来管理此域对象时,我添加了 jackson-datatype-jsr310 gradle 依赖项,以便解析 YearMonth JSON 值(例如:“2016” -04") 由 Jackson 插入此字段:

compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.6.1'

当 POST 到此端点时,JSON 文档中包含的 YearMonth 值被正确解析为 YearMonth 字段,并且整个对象成功存储为 MongoDB 上的文档。在mongo上查找这个文档证明:

> db.console.find()
{ "_id" : ObjectId("575f837ca75df1fc7e5f4f96"),
"_class" : "xxx.yyy.Console",
"name" : "Console 1",
"releaseMonth" : { "year" : 1988, "month" : 10 },
"vendor" : "VENDOR_1" }

但是,当我尝试从 REST Controller 获取该资源时,MongoDB 客户端无法将此 YearMonth 值绑定(bind)到 Java 对象中:

GET localhost:8080/consoles

回应:

{
"timestamp": 1465954648903,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.data.mapping.model.MappingException",
"message": "No property null found on entity class java.time.YearMonth to bind constructor parameter to!",
"path": "/consoles"
}

我认为 MongoDB Java 客户端缺乏对 Java 8 的 YearMonth 值的内置支持,但由于它能够保存它们,所以这似乎被排除了。我在这里缺少什么?

最佳答案

我能够通过创建 Custom Converter 来解析这个对象。 :

@Component
public class DBObjectToYearMonthConverter implements Converter<DBObject, YearMonth> {
@Override
public YearMonth convert(DBObject source) {
return YearMonth.of(
(int) source.get("year"),
(int) source.get("month")
);
}
}

并在 Application 类上设置 CustomConversions @Bean:

@Bean
public CustomConversions getCustomConversions() {
return new CustomConversions(Arrays.asList(
new DBObjectToYearMonthConverter()
));
}

欢迎其他选项。

关于java - 存储在 mongodb 上的 YearMonth 字段无法解析回对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37824751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com