Spring Mongo数据库查询中未返回嵌套字段

时间:2018-01-21 16:48:41

标签: spring mongodb mongodb-query spring-data spring-data-mongodb

我有以下两个文件:

@Document(collection = "projects")
public class Project {

    @Id
    private String id;
    private String name;
    @Indexed(unique = true)
    private String slug;

    private List<Component> components;
    private List<Feature> features;
    private List<Text> texts;

    // constructors, getters and setters omitted
}

public class Text {

    private String key;
    private String defaultText;
    private String comment;

    private String featureUsing;
    private List<String> componentsUsing;

    // constructors, getters and setters omitted

}

基本上我在项目中有一系列文本。

目前这是我唯一的文件:

{
    "_class": "org.aribeiro.i18n.entities.Project",
    "_id": "5a64b8b65aa0334ada6eced6",
    "components": [
        {
            "name": "Find and Ring portal",
            "slug": "find-and-ring-portal"
        }
    ],
    "features": [
        {
            "name": "Find and Ring",
            "slug": "find-and-ring"
        }
    ],
    "name": "Project 2",
    "slug": "project-2",
    "texts": [
        {
            "comment": "This is to show the title",
            "componentsUsing": [
                "find-and-ring-portal"
            ],
            "defaultText": "Find and Ring",
            "featureUsing": "find-and-ring",
            "key": "findringportal.title"
        }
    ]
}

我想只获得与以下过滤器匹配的文本部分:

{'texts.key': 'findringportal.title' }

所以我在我的TextsRepository中配置了这个查询:

@Query(value = "{'texts.key': ?0 }", fields = "{ 'texts.key' : 1, 'texts.defaultText': 1 }")
Text findByKey(String key);

TextsRepository是:

public interface TextsRepository extends MongoRepository<Text, String> {

    @Query(value = "{'texts.key': ?0 }", fields = "{ 'texts.key' : 1, 'texts.defaultText': 1 }")
    Text findByKey(String key);

}

问题是,在执行该查询时,我得到一个null。获取某些数据的唯一方法是使其返回Project实例,并仅返回定义的字段。但是,有没有办法让它成为嵌套实体的编组?

1 个答案:

答案 0 :(得分:1)

几点意见

问题是,在执行该查询时,我得到一个null。 - &gt;当然,您将获得null,因为您的存储库是public class DirectionExample { public enum Direction { EAST, WEST, NORTH, SOUTH; } public Direction validateDirection(final String direction) throws IllegalArgumentException { return Direction.valueOf(direction); } public static void main(String[] args) { try { DirectionExample example = new DirectionExample(); System.out.println(example.validateDirection("EAST").name()); // Get ready to catch Error: java.lang.IllegalArgumentException: // No enum constant DirectionExample.Direction.east System.out.println(example.validateDirection("east").name()); } catch (IllegalArgumentException iae) { System.err.println(iae); } finally { System.out.println("Fixed Return Type using enum"); } } } ,它将在数据库中查找无法找到的名为TextsRepository的集合。
您在数据库中只有texts个集合

projects

您的查询是正确的,但您应该针对ProjectRepository执行此操作。

@Document(collection = "projects")  

查询方法的返回类型应该可以分配给托管域类型(在您的案例中为Project)。

相关问题