java - spring-data-mongodb optional query parameter -
i using spring-data-mongodb.
i want query database passing optional parameter in query.
i have domain class.
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 }
my controller:
@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; }
here key , username optional query parameters.
if pass 1 of them should return matching document given key or username.
my service method is:
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)); }
repository:
@query("{ $or : [ {'key':?0},{'username':?1},{categories:{$in: ?2}}] }") list<doc> findbycategories(string key, string username,list<string> categories, pageable pageable);
but using above query not returns document either given key or username. wrong in query?
this how making request http://localhost:8080/document/getbycategory?key=key_one&username=ppotdar&categories=category1&categories=category2
personally, i'd ditch interface-driven repository pattern @ point, create dao @autowire
s mongotemplate object, , query db using criteria
instead. way, have clear code isn't stretching capabilities of @query
annotation.
so, (untested, pseudo-code):
@repository public class docdaoimpl implements docdao { @autowired private mongotemplate mongotemplate; public page<doc> findbycategories(userrequest request, pageable pageable){ //go through user request , make 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 refactored method, given query , pageable. q.with(sort); //build sort pageable. q.limit(limit); //build pageable list<doc> results = mongotemplate.find(q, doc.class); return makepage(results, pageable, count); } ... }
i know flies in face of trend towards runtime generation of db code, mind, it's still best approach more challenging db operations, because it's loads easier see what's going on.
Comments
Post a Comment