Mongo的morphia讀取Map<String, List<Object>>類型數據的問題

      最近一直使用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爲[ ]的數據保存到數據庫中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章