【问题标题】:Get Embed Document based on DBRef in MongoDB using Spring data使用 Spring 数据在 MongoDB 中获取基于 DBRef 的 Embed Document
【发布时间】:2021-09-15 13:27:23
【问题描述】:

我正在开发一个 Spring Boot 应用程序。我有 2 个模型是

个人实体

@Data
@Document(collection = "products")
public class ProductEntity implements Serializable {

    private static final long serialVersionUID = -8118791879505582652L;

    @MongoId(FieldType.STRING)
    private String id;

    @Indexed
    @Field("name")
    private String name;
    
    @Field("category")
    @DBRef(lazy = true)
    private CategoryEntity category;
    
    // getters and setters
}

类别实体

@Data
@Document(collection = "categories")
public class CategoryEntity implements Serializable {

    private static final long serialVersionUID = -636356399519451958L;

    @MongoId(value = FieldType.STRING)
    private String id;

    @Field("name")
    private String name;

    @Field("desc")
    private String desc;
    
    public CategoryEntity(String id) {
        super();
        this.id = id;
    }
    // getters and setters
}

当我将数据保存到数据库中时,存储的数据是

产品文档

{
    "_id": {
        "$oid": "6141eeab92432109463ae8c4"
    },
    "name": "Adidas Running Shoes",
    "category": {
        "$ref": "categories",
        "$id": "614049d91042cf40b5b9b304"
    }
}

分类文档

{
    "_id": {
        "$oid": "614049d91042cf40b5b9b304"
    },
    "name": "Shoes",
    "desc": "Men's running Shoes",
}

但是当我尝试使用 Spring-Data-MongoDB 对 findAll()ProductEntity 数据进行处理时,该类别将返回 null

public List<ProductModel> getProducts() {
    List<ProductEntity> entities = productRepo.findAll();
    return entities.stream().map(entity -> {
        ProductModel product = new ProductModel();
        BeanUtils.copyProperties(entity, product);
        if (Objects.nonNull(entity.getCategory())) {
            BeanUtils.copyProperties(entity.getCategory(), product.getCategory());
        }
        return product;
    }).collect(Collectors.toList());
}

我需要输出格式如下。

{
    "_id": {
        "$oid": "6141eeab92432109463ae8c4"
    },
    "name": "Adidas Running Shoes",
   
    "category": {
        "_id": {
            "$oid": "614049d91042cf40b5b9b304"
        },
        "name": "Shoes",
        "desc": "Men's running Shoes",
    }
}

请告诉我如何获得所需的输出。

【问题讨论】:

    标签: mongodb spring-boot spring-data-mongodb dbref


    【解决方案1】:

    我做了一个小改动,问题已经解决。我变了

    来自

    @MongoId(value = FieldType.STRING)
    private String id; 
    

    @MongoId(value = FieldType.OBJECT_ID) 
    private ObjectId id;
    

    在实体和代码中都有效!

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      相关资源
      最近更新 更多