Mongo的morphia读取Map<String, List<Object>>类型数据的问题

来源:互联网 发布:手机看电影软件排行 编辑:程序博客网 时间:2024/06/05 02:55

      最近一直使用morphia,给mongo数据查询带来很多遍历,但是最近项目遇到了一个严重的问题,在从Mongo数据库中查询Map<String, List<Object>>字段时,针对value值为空list时(即[ ]),竟然读到数据的严重问题,具体描述如下:

 1.Entity数据结构:     

import org.mongodb.morphia.annotations.Embedded;import org.mongodb.morphia.annotations.Property;import java.util.List;import java.util.Map;/** * Created by zhangzh on 2017/6/14. */public class MyEntity {    @Property("id")    private String id;    @Property("name")    private String name;    @Property("description")    private String description;        @Embedded    private Map<String, List<SubEntity>> mySubEntity;    public static class SubEntity {        @Property("subName")        private String subName;        @Property("subDescription")        private String subDescription;    }}

2.数据在mongo数据库中的存储格式:

 

{ "_id" : ObjectId("5940b1643db71d944c800445"), "name" : "myEntity name test", "description" : "myEntity description test", "MapEntity" : {        "entity1" : [            {                "name" : "lance","description":"lance-description"            }        ],"entity2" : []    }}

3.读取数据库中数据的代码:

  

import org.bson.types.ObjectId;import org.mongodb.morphia.Datastore;import org.mongodb.morphia.query.Query;/** * Created by zhangzh on 2017/6/14. */public class MyEntityDao {    private Datastore datastore;    public MyEntity getMyEntityById(String Id) {        Query<MyEntity> query = datastore.createQuery(MyEntity.class);        query.criteria("_id").equal(new ObjectId(Id));        return query.get();    }}

 4. 读取结果:

{ "_id" : ObjectId("5940b1643db71d944c800445"), "name" : "myEntity name test", "description" : "myEntity description test", "MapEntity" : {        "entity1" : [            {                "name" : "lance","description":"lance-description"            }        ],"entity2" : [    {                "name" : "lance", "description":"lance-description"            } ]    }}

5.结果分析:

     5.1  数据库中保存的"entity2" : 为空[ ] ,而使用morphia获取到的Entity为

"entity2" : [    {                "name" : "lance", "description":"lance-description"            } ]
 和entity1 相等,MyEntityDao获取的值错误,会给业务带来严重的问题。

    5.2  当"entity2"值不是[ ]时,能够获取到正确的结果。


  6.解决方式:

   将MyEntity数据保存到Mongo数据库中时,禁止Map<String, List<SubEntity>> mySubEntity的map中的key为[ ]的数据保存到数据库中。

阅读全文
0 0