Tim*_*Tim 3 java collections mongodb spring-data
我在映射我的内部收藏时遇到了一些问题。项目可以有不同的内容类型。这是我的项目类:
@Document(collection = "items")
public class Item{
@Id
private ObjectId id;
private List<? super Content> content;
...
}
Run Code Online (Sandbox Code Playgroud)
Content 是这个 Item 不同内容的基类。
public class YoutubeVideo implements Content{
private String url;
}
public class Image implements Content{
private String location;
}
...
Run Code Online (Sandbox Code Playgroud)
在内容集合中保存(保存完成没有问题)带有一个图像和两个 YoutubeVideo 类的项目后,我得到了这个 JSON
{ "_id" : { "$oid" : "4e423dcf7f3a0d12265da46c"}
"content" : [
{ "location" : "hdd path"} , { "url" : "url path"} , { "url" : "url path"}
]}
Run Code Online (Sandbox Code Playgroud)
这不是我希望看到的 JSON。并且可以理解为什么无法加载和反序列化此文档。
java.lang.RuntimeException: Can not map ? super trngl.mongo.domain.content.Content
Run Code Online (Sandbox Code Playgroud)
你将如何映射这种对象?我不想手动序列化和反序列化对象。是否可以?
找到兴趣转换器类:mapping-explicit-converters
小智 5
就像一个仅供参考(因为我们在试图弄清楚为什么我们将我们的对象作为LinkedHashMaps成员返回之后寻找了这个早上好),这个问题也会发生(在 1.0.2.RELEASE 中),当您尝试存储aCollection<Content>形式:
@Document(collection = "items")
public class Item{
@Id
private ObjectId id;
private Collection<Content> content;
...
}
Run Code Online (Sandbox Code Playgroud)
如上所述,解决方案是将其切换为List<Content>.