I have a RestController that have one GET method with @RequestParam Map<String, String> Then I pass the Map to a pojo to store it in fields with setters. and now i want to pass these field to a methods from repository, i'm doing it like so in a different class:
if (map.size() == 1) {
return repo.methodWithOneParam(pojo.getFieldOne());
}
if (map.size() == 2) {
return repo.methodWithTwoParam(pojo.getFieldOne(),pojo.getFieldTwo);
}
if (map.size() == 3) {
return repo.methodWithThreeParam(pojo.getFieldOne(),pojo.getFieldTwo,pojo.getFieldThree);
}
Can I get rid of these if-if-else statements somehow dynamically because I have like 15 or more methods like those in the repo. The Repo stores methods to connect to database.
CodePudding user response:
A switch/case construct is a LITTLE cleaner:
int mapSize = map.size();
switch (mapSize) {
case 1: return repo.methodWithOneParam(pojo.getFieldOne());
break;
case 2: return repo.methodWithTwoParam(pojo.getFieldOne(), pojo.getFieldTwo);
break;
case 3: return repo.methodWithThreeParampojo.getFieldOne(), pojo.getFieldTwo, pojo.getFieldThree);
break;
default: return "No handler for call with " mapSize " params.";
break;
}
CodePudding user response:
Where you MAY be getting into trouble, making your controller code rigid and verbose is in defining all those case-specific methods in your repository. Maybe you should expose just one repo method "methodWithAnyNumberOfParams(Map<String, String> paramMap)" and have any custom and/or dynamic code in the implementation (default method annotated @Query etc.) Then your controller method consists in return repo.methodWithAnyNumberOfParams(inputMap); ...and little else.
I am inferring (a fancy word for "wild guess") that you are allowing for any number of filter criteria to be passed in in order to dynamically generate a SQL WHERE clause, anywhere from
SELECT * FROM CRIMINAL_CONVICTIONS WHERE LAST_NAME = 'Capone'
...to the above plus any/all of the below:
AND CRIME_TYPE = 'Felony'
AND GUN_USED = 'Y'
AND STATE = 'IL'
AND DECADE = '1920s'
etc. BTW, be certain your frameword does NOT under any circumstances permit SQL injection. Use predefined constants and/or enums to match incoming keys.