How to map document with dynamic keys to a Spring MongoDb entity class(如何将具有动态键的文档映射到 Spring MongoDb 实体类)
问题描述
我有一个可以有动态键名的文档:
I have a document that can have dynamic key names:
{
"_id" : ObjectId("51a29f6413dc992c24e0283e"),
"envinfo" : {
"appName" : "MyJavaApp",
"environment" : {
"cpuCount" : 12,
"heapMaxBytes" : 5724766208,
"osVersion" : "6.2",
"arch" : "amd64",
"javaVendor" : "Sun Microsystems Inc.",
"pid" : 44996,
"javaVersion" : "1.6.0_38",
"heapInitialBytes" : 402507520,
}
这里 envinfo
的键是事先不知道的.在 Spring Data Mongodb 中创建将映射此文档的实体类的最佳方法是什么?
Here envinfo
's keys are not known in advance.
What is the best way to create an entity class in Spring Data Mongodb which will map this document?
推荐答案
这就是我要做的.
class EnvDocuemnt {
@Id
private String id; //getter and setter omitted
@Field(value = "envinfo")
private BasicDBObject infos;
public Map getInfos() {
// some documents don't have any infos, in this case return null...
if ( null!= infos)
return infos.toMap();
return null;
}
public void setInfos(Map infos) {
this.infos = new BasicDBObject( infos );
}
}
这样,getInfos()
返回一个 Map
,您可以在需要时使用 String 键进行探索,并且可以嵌套 Map.
This way, getInfos()
returns a Map<String,Object>
you can explore with String keys when needed, and that can have nested Map.
对于你的依赖,最好不要直接暴露 BasicDBObject
字段,这样可以在不包含任何 MongoDb 库的代码中通过接口使用.
For your dependencies, it is better not to expose the BasicDBObject
field directly, so this can be used via interface in a code not including any MongoDb library.
注意,如果envinfo中有一些经常访问的字段,那么最好将它们声明为你的类中的字段,有一个直接访问器,这样就不用花太多时间一遍又一遍地浏览地图.
Note that if there is some frequent accessed fields in envinfo, then it would be better to declare them as fields in your class, to have a direct accessor, and so not to spend to much time in browsing the map again and again.
这篇关于如何将具有动态键的文档映射到 Spring MongoDb 实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将具有动态键的文档映射到 Spring MongoDb 实体类


基础教程推荐
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01