spring数据mongodb映射动态场
我在我的java类中有这个模型
@Document public class Template { private String type; private String code; @Version Long version; }
我需要添加一个名为template的新字段,并将此字段映射为动态,换句话说,我会像这样建模一个文档
{ _id: 'id' type:'myType', code:'myCode' template:{ someFiled:[ { subField1:'value1', subField2:'value2' }, { sub1Field1:'1value1', sub1Field2:'1value2' } ....................... ], otherField:[ { otherField1:'value1', otherField2:'value2' } ], ......... }, version:1000L }
有没有办法将字段注释为动态?
解
@Document public class Template { private String type; private String code; private Map template; @Version Long version; }
我发现了一个完美的解决方案。 以我的项目为例:
@Data @Document(collection = "logs") public class Log { @Id private String id; private Object data; // data field can be a string public void setData(String str) { data = str; } // data field can be a {} public void setData(JsonObject jsonObject) { data = new BasicDBObject(jsonObject.getMap()); } // data can be a [] public void setData(JsonArray jsonArray) { BasicDBList list = new BasicDBList(); list.addAll(jsonArray.getList()); data = list; } }
将data
字段声明为Object
类型,为它实现3种setter。
以下是测试用例:
@RunWith(SpringRunner.class) @SpringBootTest public class LogRepositoryTest { @Autowired private LogRepository logRepository; @Test public void test() { Log strLog = new Log(); strLog.setData("string here"); logRepository.save(strLog); Log objLog = new Log(); objLog.setData(new JsonObject().put("key", "value").put("obj", new JsonObject())); logRepository.save(objLog); Log aryLog = new Log(); aryLog.setData(new JsonArray().add("a").add("b").add("c")); logRepository.save(aryLog); } }
结果如下:
{ "_id" : ObjectId("5a09fa46a15b065268a0a157"), "_class" : "ltd.linkcon.spider.domain.Log", "data" : "string here" } { "_id" : ObjectId("5a09fa46a15b065268a0a158"), "_class" : "ltd.linkcon.spider.domain.Log", "data" : { "key" : "value", "obj" : [ ] } } { "_id" : ObjectId("5a09fa46a15b065268a0a159"), "_class" : "ltd.linkcon.spider.domain.Log", "data" : [ "a", "b", "c" ] }
- 如何在java apache数学中使用SimplexSolver或SimplexOptimizer?
- 从String创建URL
- 没有’MSysObjects’的读取权限
- BufferedReader中的缓冲区大小是多少?
- 你可以在.jar中存储数据吗?
- 当要解析的元素是json字符串的元素时,使用gson解析json的最简单方法是什么?
- ClassNotFoundException在修改后的SimpleShortestPathsVertex上运行GiraphRunner
- Spring启动 – 由于缺少EmbeddedServletContainerFactory bean,无法启动EmbeddedWebApplicationContext
- Glassfish 4扫描@PostConstruct并禁用CDI