spring 数据 mongodb 同一集合中的多个实体

spring data mongodb multiple entity in same collection

我处于一种情况,我必须将属于多个实体的数据存储在一个集合中。但是当我查询然后返回时,我不希望结果中出现不需要的记录。我们如何使用 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 returns 仅那些文档结构与 AnimalEntity 相同的记录。

非常感谢您抽出宝贵的时间和耐心参与此次咨询。

MongoDB 自动将 _class 字段添加到集合中的实体。虽然这不是最好的解决方案,但您可以试试这个:

@Query("_class:your package name here.AnimalEntity")
public AnimalEntity findAllAnimals();