使用mongoTemplate在嵌入式文档字段上进行MongoDB Projection

时间:2018-03-28 22:25:34

标签: java mongodb projection mongotemplate mongorepository

在我的java应用程序中,我想要检索嵌入文档的字段。 这是我的pojo:

我的User.class

public class User implements Comparable<User> {

    @Id
    private String username;

    private String ownerFirstname;

    private String ownerLastname;

    @DBRef
    @CascadeSave
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Role role;
}

Role.class

@Document
@JsonDeserialize(using = RoleDeserializer.class)
public interface Role {

    String getId();

    void setId(String id);

}

Society.class

@Document(collection = "role")
public class Society implements Role {

    @Id
    private String id;

    private String name;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Address societyAddress;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String vatNumber;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private long birthday;

    private List<ProductResearch> productResearches;

    @DBRef
    private List<Advertisement> advertisementOwnedList;

    @DBRef
    private List<OrderRequest> orderRequests;

    private UserType type;
}

我对adsOwnedList字段感兴趣,但我无法得到它。 使用MongoTemplate我尝试进行投影:

Query query = Query.query(Criteria.where("_id").is(user.getUsername()));
query.fields().include("role.advertisementOwnedList;");
User user1 = mongoTemplate.findOne(query, User.class);

或使用MongoRepository:

@Query(value = "{ '_id' : ?0}", fields = "{ '_id': 0 , 'role' : 1 ,
'role.advertisementOwnedList' : 1 }") 
User getRoleAdvertisementOwnedList(String username);

然而,Role是一个接口,我总​​是得到例外:

org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate it.bmv.backend.model.Role using constructor NO_CONSTRUCTOR with arguments 

    at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:64)
    at org.springframework.data.convert.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:83)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:259)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:239)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1222)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.access$200(MappingMongoConverter.java:85)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1170)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getValueInternal(MappingMongoConverter.java:880)
    at org.springframework.data.mongodb.core.convert.DefaultDbRefResolverCallback.resolve(DefaultDbRefResolverCallback.java:59)
    at org.springframework.data.mongodb.core.convert.DefaultDbRefResolver.resolveDbRef(DefaultDbRefResolver.java:98)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter$2.doWithAssociation(MappingMongoConverter.java:313)
    at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:360)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:296)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:239)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:199)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:195)
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:85)
    at org.springframework.data.mongodb.core.MongoTemplate$ReadDbObjectCallback.doWith(MongoTemplate.java:2324)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindOneInternal(MongoTemplate.java:1925)
    at org.springframework.data.mongodb.core.MongoTemplate.doFindOne(MongoTemplate.java:1736)
    at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:606)
    at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:601)
    at it.bmv.backend.UserTest.getAdvTest(UserTest.java:93)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.bmv.backend.model.Role]: Specified class is an interface
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:99)
    at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:61)
    ... 50 more

如何获取角色嵌套文档的字段?

1 个答案:

答案 0 :(得分:1)

由于我的评论可能不够明确,我会尝试给出更详尽的答案。

对于内部测试工具,我正在写作,如果我有时间,我想出了包含一个或多个不同场景的任务的想法。场景只是需要执行的某个预定义测试。任务还包含一个测试用例列表,其中包含相应测试的当前状态。

我们的简化模型看起来像这样:

@Getter
@Setter
@Document(collection = "task")
public class TaskEntity implements Serializable, NamedResource {

  @Id
  private String id;
  private String name;
  private String testerName;
  ...
  @DBRef
  private List<ScenarioEntity> testsToExecute = new ArrayList<>();
  ...
  private List<TestCase> performedTests = new ArrayList<>();
  ...
}

场景实体维护在不同的集合中,仅在任务条目中作为参考提供。但是,测试用例是任务中的嵌入式文档。

Spring Data允许通过引入一个单独的接口来定义实体或子文档的视图,该接口包含您感兴趣的实体getter方法的子集。

例如,TaskView包含以下内容:

public interface TaskView extends NamedResource {

  String getTesterName();

  @Value("#{target.testsToExecute}")
  List<ScenarioView> getTestsToExecute();
}

ScenarioView看起来像这样:

public interface ScenarioView extends NamedResource {

}

因为它只继承了NamedResource

中的方法
public interface NamedResource {
  String getId();
  String getName();
}

另一方面,TestCaseView稍微复杂一些,因为它还从包含的条目中检索属性:

public interface TestCaseView {

  String getId();
  String getTaskId();
  Date getStart();
  Date getEnd();
  @Value("#{target.scenario.id}")
  String getScenarioId();
  @Value("#{target.secnario.name}")
  String getScenarioName();
  @Value("#{target.result.result.name()}")
  String getJobResult();
}

为了使用所有这些接口,TaskRepository确实定义了以下查询:

public interface TaskRepository extends MongoRepository<TaskEntity, String> {

  @Query("{ '_id': ?0 }")
  TaskEntity findById(String id);

  @Query("{ }")
  Page<TaskView> findPageable(Pageable pageable);

  @Query("{ '_id': ?0, 'performedTests': { 'id': ?1 } }")
  TestCase findTestCaseByIdViaTaskId(String id, String uuid);

  @Query("{ '_id': ?0, 'performedTests': { } }")
  List<TestCase> findTestsCasesForTask(String id);

  @Query("{ '_id': ?0, 'performedTests': { } }")
  Page<TestCaseView> findTestCaseViews(String id, Pageable pageable);

  ...
}

从代码中可以看出,Spring Data允许直接在存储库接口而不是实体类中定义视图接口,因此只检索数据的子集或聚合。