spring-data-mongodb可选查询参数

mah*_*wde 5 java spring annotations mongodb spring-data-mongodb

我正在使用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
}
Run Code Online (Sandbox Code Playgroud)

我的控制器:

@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;
    }
Run Code Online (Sandbox Code Playgroud)

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

如果我传递其中任何一个,它应该返回具有给定密钥或用户名的匹配文档.

我的服务方法是:

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));
    }
Run Code Online (Sandbox Code Playgroud)

库:

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

但是通过使用上面的查询,它不会返回具有给定键或用户名的文档.我的查询有什么问题?

这就是我发出请求的方式 http:// localhost:8080/document/getByCategory?key = key_one&username = ppotdar&categories = category1&categories = category2

Mic*_*ear 1

就我个人而言,我会放弃接口驱动的存储库模式,创建一个@Autowire包含 MongoTemplate 对象的 DAO,然后使用 aCriteria来查询数据库。这样,您就拥有了不会扩展@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);
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

我知道这与运行时生成数据库代码的趋势背道而驰,但在我看来,它仍然是更具挑战性的数据库操作的最佳方法,因为它更容易看到实际发生的情况。