在DBRef对象上使用Spring Data Projection

时间:2016-04-15 10:02:44

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

我开始使用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> {

}

问题

当我要求竞争资源时,我没有得到足够的参与者信息 - 只有&#34;频率&#34;字段显示。我已经尝试过使用@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"
    }
]
}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

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

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

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

    String getName();

    Person getOrganizer();

    @Value("#{target.getParticipants()}")
    List<Participant> getParticipants();
}