1. 程式人生 > >Mongo的morphia讀取Map>型別資料的問題

Mongo的morphia讀取Map>型別資料的問題

      最近一直使用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 lance 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 lance  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為[ ]的資料儲存到資料庫中。