我处于必须将属于多个实体的数据存储在单个集合中的情况。但是当我查询然后返回时,我不希望结果中出现不需要的记录。我们如何使用 spring 实现这一目标?以下是我到目前为止所做的。
1.我在实体中给出相同的集合名称,如下所示。
@Document(collection = "livingThings")
@Data
public class AnimalEntity {
//contains id, type, bla, bla
}
@Document(collection = "livingThings")
@Data
public class HumanEntity {
//contains id, gender, address
}
2.我创建了独立的mongoRepository接口
public interface AnimalRepository implements MongoRepository<AnimalEntity, String> {
}
public interface HumanRepository implements MongoRepository<HumanEntity, String> {
}
3.问题是
当我执行animalRepo.findAll 或humanRepo.findAll 时,我会得到集合中所有可用的记录。
4. 我的期望
AnimalRepo.findAll 仅返回文档结构与 AnimalEntity 相同的记录。
非常感谢您抽出时间和耐心参加此次咨询。
MongoDB 自动将 _class 字段添加到集合中的实体。即使这不是最佳解决方案,您也可以尝试以下操作:
@Query("_class:your package name here.AnimalEntity")
public AnimalEntity findAllAnimals();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句