【问题标题】:Spring Data REST, QueryDSL and HashMaps - Null Predicate from URL when referring to HashMap propertiesSpring Data REST、QueryDSL 和 HashMaps - 引用 HashMap 属性时来自 URL 的空谓词
【发布时间】:2017-03-15 12:17:54
【问题描述】:

我有一个实体对象,我使用 Spring Data MongoDB 将其保存在 MongoDB 中,并公开一个 REST API 来查询它。实体如下所示:

Entity.java

 @Document
 public class Entity {
      @Id
      String id;
      Map<String, String> properties;
   }

对应的Spring Data存储库如下。它利用 Spring Data MongoDB 与 QueryDsl 的集成:

EntityRepository.java

public interface EntityRepository extends MongoRepository<Entity, String>
                                         ,QueryDslPredicateExecutor<Entity> {
}

这是我查询存储实体的控制器:

EntityController.java

@RestController
@RequestMapping(value = "/entities")
public class EntityController {

    private static final Logger logger = LoggerFactory.getLogger(EntityController.class);

    @Autowired
    EntityRepository entityRepository;

    @RequestMapping(method = RequestMethod.GET)
    public Page<Entity> findAllEntities(Pageable pageable) throws ResourceQueryException {
        return entityRepository.findAll(pageable);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/q")
    public Page<Entity> filterEntities(
            @QuerydslPredicate(root = Entity.class) Predicate predicate,
            Pageable pageable) {
        return entityRepository.findAll(predicate,pageable);
    }

}

当我点击 url localhost:8080/entities/q?id=xxx 时,它按预期工作。但是,当我点击 url localhost:8080/entities/q?properties.p1=v1(查询 Map 属性的键和值)时,我的方法中得到一个空谓词,因此所有实体都被返回。

如何让它正常工作?

【问题讨论】:

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


    【解决方案1】:

    您应该将您的 properties 字段存储为 List of key-value 对,然后才能在其中进行搜索。

    您的查询应该使用下一个结构:

    {  id : "1233454",
       properties : [ 
            { "key : "key", "value" : "value" }
       ]
    }
    

    【讨论】:

    • 感谢您的回答!但是在使用这个模式时,查询具有特定属性的对象变得越来越困难,我不得不求助于 $elematch 构造。 Spring Data Web 中对此的支持似乎严重不足。我在从 URL 自动形成 Predicate 对象时遇到了问题,所以我不得不求助于上面提到的 Map 方法。
    • 但实际上您可以像这里一样编写自定义绑定:github.com/spring-projects/spring-data-examples/tree/master/web/… 结构应该像我提到的那样,并且像“properties.p1 = p2”这样的查询应该不起作用,或者它可以从控制台为您工作例子?
    猜你喜欢
    • 2015-01-21
    • 2016-01-08
    • 1970-01-01
    • 2018-04-06
    • 2020-09-18
    • 2012-11-02
    • 2023-04-04
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多