栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Spring Data Mongo DB中聚合嵌套对象并避免PropertyReferenceException?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Spring Data Mongo DB中聚合嵌套对象并避免PropertyReferenceException?

我找到了一个解决方案,它是两个问题的组合:

PropertyReferenceException
的确造成的,因为
attributes
Map<String,String>
这意味着它的蒙戈没有计划。

该错误消息

No property brand found for type String! Traversed path:Profile.attributes.
表示该
Map
对象中没有品牌属性。

为了解决此问题而不接触我的原始

Profile
类,我必须创建一个新的自定义类,该类将映射
attributes
到具有我要添加的属性的attribute对象,例如:

public class StatsAttributes {  @JsonProperty  private String brand;  @JsonProperty  private String language;  public StatsAttributes() {}  }

然后,我创建了一个自定义变量

StatsProfile
,它将利用我的自定义变量,
StatsAttributes
并且类似于原始
Profile
对象,而无需对其进行修改。

@documentpublic class StatsProfile {  @JsonProperty  private String user;  @JsonProperty  private StatsAttributes attributes;  public StatsProfile() {}  }

这样,我就消除了在聚合中

PropertyReferenceException
使用新类的问题
StatsAggregation

AggregationResults<Stats> groupResults      = mongoTemplate.aggregate(agg, StatsProfile.class, Stats.class);

但是我不会得到任何结果。该查询似乎在数据库中找不到任何文档。那就是我意识到生产mongo对象具有

"_class:com.company.dao.model.Profile"
绑定到该
Profile
对象的字段的地方。

经过一番研究,对于新的

StatsProfile
要工作,它必须是一个
@TypeAlias("Profile")
。环顾四周后,我发现还需要精确定义集合名称,这将导致:

@document(collection = "profile")@TypeAlias("Profile")public class StatsProfile {}

有了所有这些,终于奏效了!

我想这不是最漂亮的解决方案,我希望我不需要创建一个新的Profile对象,而只是将其

attributes
视为
StatsAttributes.class
mongoTemplate查询中的某种方式。如果有人知道怎么做,请分享
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402951.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号