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

时间:2016-06-15 01:40:38

标签: java spring mongodb mongodb-java

背景:我的应用程序建立在 Spring Data REST MongoDB存储库之上。

考虑这个带有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控制器(由Data REST自动)来管理这个域对象时,我已经添加了jackson-datatype-jsr310 gradle依赖,以便解析YearMonth JSON值(例如:&#34; 2016-04& #34;)杰克逊进入这个领域:

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控制器获取该资源时,MongoDB客户端无法将此YearMonth值绑定到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值的内置支持,但由于它能够保存它们,因此似乎排除了这一点。我在这里错过了什么?

1 个答案:

答案 0 :(得分:1)

我能够通过创建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()
    ));
}

欢迎其他选择。