Spring Data MongoDB 可选查询参数

6
我是使用spring-data-mongodb。
我想通过传递一些可选参数来查询数据库。
我有一个领域类。
public class Doc {  
    @Id
    private String id;

    private String type;

    private String name;

    private int index;  

    private String data;

    private String description;

    private String key;

    private String username;
    // getter & setter
}

我的控制器:

@RequestMapping(value = "/getByCategory", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON)
    public Iterable<Doc> getByCategory(
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "page", required = false, defaultValue = "0") int page,
            @RequestParam(value = "size", required = false, defaultValue = "0") int size,
            @RequestParam(value = "categories") List<String> categories)
            throws EntityNotFoundException {
        Iterable<Doc> nodes = docService.getByCategory(key, username , categories, page, size);
        return nodes;
    }

这里的Keyusername是可选查询参数。

如果我传递其中任意一个参数,则应返回具有给定key或username的匹配文档。

我的服务方法是:

public Iterable<Doc> getByCategory(String key, String username, List<String> categories, int page, int size) {

        return repository.findByCategories(key, username, categories, new PageRequest(page, size));
    }

仓库:

@Query("{ $or : [ {'key':?0},{'username':?1},{categories:{$in: ?2}}] }")    
List<Doc> findByCategories(String key, String username,List<String> categories, Pageable pageable);

但是使用以上查询语句并不能返回给定的关键字或用户名的文档。我的查询语句哪里出错了?
这是我发起请求的方法: http://localhost:8080/document/getByCategory?key=key_one&username=ppotdar&categories=category1&categories=category2

你可以开始设置MongoDB Profiler以记录所有操作(包括查询),使用命令db.setProfilingLevel(2),然后查看你正在执行的确切查询。记得在完成后将其设置为0。 - araknoid
2个回答

1

个人而言,我会放弃基于接口的存储库模式,创建一个DAO,使用@Autowire注入MongoTemplate对象,并使用Criteria查询数据库。这样,您就可以拥有清晰的代码,而不需要扩展@Query注释的功能。

因此,类似于以下内容(未经测试的伪代码):

@Repository
public class DocDAOImpl implements DocDAO {
    @Autowired private MongoTemplate mongoTemplate;

    public Page<Doc> findByCategories(UserRequest request, Pageable pageable){
        //Go through user request and make a criteria here
        Criteria c = Criteria.where("foo").is(bar).and("x").is(y); 
        Query q = new Query(c);
        Long count = mongoTemplate.count(q);

        // Following can be refactored into another method, given the Query and the Pageable.
        q.with(sort); //Build the sort from the pageable.
        q.limit(limit); //Build this from the pageable too
        List<Doc> results = mongoTemplate.find(q, Doc.class);
        return makePage(results, pageable, count);
    }

    ...
}

我知道这与运行时生成数据库代码的趋势相悖,但在我看来,对于更具挑战性的数据库操作,仍然是最好的方法,因为更容易看到实际发生了什么。

0

根据输入值过滤查询的部分内容并不直接支持。然而,可以使用@Query$and运算符和一些SpEL来实现。

interface Repo extends CrudRepository<Doc,...> {

  @Query("""
         { $and : [ 
            ?#{T(com.example.Repo.QueryUtil).ifPresent([0], 'key')}, 
            ?#{T(com.example.Repo.QueryUtil).ifPresent([1], 'username')},
            ... 
         ]}
         """)
  List<Doc> findByKeyAndUsername(@Nullable String key, @Nullable String username, ...)

  class QueryUtil {
    public static Document ifPresent(Object value, String property) {
      if(value == null) {
        return new Document("$expr", true); // always true
      }
      return new Document(property, value); // eq match
    }
  }

  // ...
}

不必通过 T(...) Type 表达式来寻址目标函数,编写一个 EvaluationContextExtension(详见:json spel)可以消除反复重复类型名称的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接