【问题标题】:Spring Data REST MongoDB: Retrieve objects of DBRef instead of hrefSpring Data REST MongoDB:检索 DBRef 的对象而不是 href
【发布时间】:2016-06-29 17:11:53
【问题描述】:

专家们您好@stackOverflow,

我们正在使用 Spring Data REST MongoDB。

是否可以预先加载子对象,而不是使用@DBRef 注释的超链接?请参考下面的Process.templates 属性。

这是我们的模型:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.ArrayList;
import java.util.List;

@Document(collection = "process")
public class Process {
    @Id
    private String id;

    private String name;

    @DBRef ///////// ------> This is the corresponding attribute <------
    private List<MergeTemplate> templates = new ArrayList<>();

这是我们的存储库:

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "process", path = "process")
public interface ProcessRepository extends MongoRepository<Process, String> {
}

FindAll API 带来指向子对象的链接

http://localhost:8080/data/process

带来以下 JSON。

{
  "_embedded" : {
    "process" : [ {
      "id" : "56d731b82b45ee21a0d2ab0a",
      "name" : "application-kit",
      "_links" : {
        ..., 
        /********** This is the attribute in question (templates) ************/
        "templates" : {
          "href" : "http://localhost:8080/data/process/56d731b82b45ee21a0d2ab0a/templates"
        }
      }
    }, ...]
}

我什至试过@DBRef(lazy=false),但没有运气。

提前致谢!

【问题讨论】:

    标签: java spring mongodb rest spring-data-rest


    【解决方案1】:

    你有两种可能:

    1. 将您的MergeResults 存储在Process 文档中(我不知道它是否适用于您的情况,但即使您有很多MergeResults,因为@987654325 这将是最佳选择@ 类似于 SQL 连接,而 MongoDB 并不擅长于此)
    2. 使用Excerpt

    使用摘录

    您可以通过以下步骤实现您的目标:

    1) 创建 Process 文档的投影

    @Projection(name = "inlineTemplates", types = { Process.class }) 
    interface InlineTemplates {
    
      String getId();
    
      String getName();
    
      // using getTemplates() inside a projection causes the information to be inlined
      List<MergeTemplate> getTemplates(); 
    }
    

    2) 编辑您的存储库

    @RepositoryRestResource(excerptProjection = InlineTemplates.class)
    interface ProcessRepository extends CrudRepository<Process, String> {}
    

    3) 前往http://localhost:8080/data/process查看结果

    注意:我没有尝试代码,只是从文档中获取说明。如果它不起作用,请见谅。

    【讨论】:

    • 完美!我不得不使用摘录。谢谢!我没有使用 excerptProjection 进行注释,而是在执行时使用了 ?projection=inlineTemplates。
    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2015-10-31
    • 2014-11-14
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多