1

我开始使用 MongoDB 数据库在一个非常简单的项目中学习 Spring Data,并且在使用 DBRef 时遇到了一些麻烦——也许在如何对 NoSQL 数据库进行建模方面

描述

我的项目应该组织一个简单的比赛,有一个组织者(CD)和一对多的参与者。因为人们可以参加多个比赛,所以我为比赛和个人制作了存储库。

完整的代码可以在 GitHub 上看到:https ://github.com/elkjaerit/rest-sample

这是基类:

public class Competition {

  @Id private String id;

  private String name;

  @DBRef
  private Person organizer;

  private List<Participant> participants = new ArrayList<>();

}


public class Participant {

  private String freq;

  @DBRef
  private Person person;
}


public class Person {
  @Id
  private String id;

  private String name;
}

存储库:

@RepositoryRestResource(collectionResourceRel = "competition", path = "competition")
public interface CompetitionRepository extends MongoRepository<Competition, String> {

}

@RepositoryRestResource(collectionResourceRel = "person", path = "person")
public interface PersonRepository extends MongoRepository<Person, String> {

}

问题

当我请求竞赛资源时,我没有获得足够的参与者信息 - 仅显示“频率”字段。我试过使用@Projection 并设法让它为组织者工作,但我不知道如何为参与者获取人员对象?

没有投影的结果

{
"_links": {
    "competition": {
        "href": "http://localhost:8080/competition/5710b32b03641c32671f885a{?projection}", 
        "templated": true
    }, 
    "organizer": {
        "href": "http://localhost:8080/competition/5710b32b03641c32671f885a/organizer"
    }, 
    "self": {
        "href": "http://localhost:8080/competition/5710b32b03641c32671f885a"
    }
}, 
"name": "Competition #1", 
"participants": [
    {
        "freq": "F0"
    }, 
    {
        "freq": "F1"
    }, 
    {
        "freq": "F2"
    }, 
    {
        "freq": "F3"
    }
]
}

并带有投影

{
"_links": {
    "competition": {
        "href": "http://localhost:8080/competition/5710b32b03641c32671f885a{?projection}", 
        "templated": true
    }, 
    "organizer": {
        "href": "http://localhost:8080/competition/5710b32b03641c32671f885a/organizer"
    }, 
    "self": {
        "href": "http://localhost:8080/competition/5710b32b03641c32671f885a"
    }
}, 
"name": "Competition #1", 
"organizer": {
    "name": "Competition organizer"
}, 
"participants": [
    {
        "freq": "F0"
    }, 
    {
        "freq": "F1"
    }, 
    {
        "freq": "F2"
    }, 
    {
        "freq": "F3"
    }
]
}

有什么建议么 ?

4

1 回答 1

0

您也许可以使用 SPEL 为您的相关文档调用 getter。

您的投影可能看起来像这样 -

    @Projection(name = "comp", types = {Competition.class})
public interface CompetitionProjection {

    String getName();

    Person getOrganizer();

    @Value("#{target.getParticipants()}")
    List<Participant> getParticipants();
}
于 2016-06-12T13:24:02.807 回答