大家好,又见面了,我是你们的朋友全栈君。
最近一直使用morphia,给mongo数据查询带来很多遍历,但是最近项目遇到了一个严重的问题,在从Mongo数据库中查询Map<String, List<Object>>字段时,针对value值为空list时(即[ ]),竟然读到数据的严重问题,具体描述如下:
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;
}
}
{
"_id" : ObjectId("5940b1643db71d944c800445"),
"name" : "myEntity name test",
"description" : "myEntity description test",
"MapEntity" : {
"entity1" : [
{
"name" : "lance",
"description":"lance-description"
}
],
"entity2" : []
}
}
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();
}
}
{
"_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.1 数据库中保存的”entity2″ : 为空[ ] ,而使用morphia获取到的Entity为
"entity2" : [
{
"name" : "lance",
"description":"lance-description"
}
]
和entity1 相等,MyEntityDao获取的值错误,会给业务带来严重的问题。
5.2 当”entity2″值不是[ ]时,能够获取到正确的结果。
将MyEntity数据保存到Mongo数据库中时,禁止Map<String, List<SubEntity>> mySubEntity的map中的key为[ ]的数据保存到数据库中。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/149548.html原文链接:https://javaforall.cn