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 实体类


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01