Methods of adding many (unspecified number) objects form database via Rest service

SztyJkmajster Z Polski :

I'm trying to write my own app. It should provide adding food products with parameters, what I was already done , further aim is to sum all property form added products, compare with daily balance, etc.

I have a problem with concept of connecting products to a meal. Im wondering if is some pretty alternative to function with specific number of (optional) parameters, witch is a certain limitation of functionality. Here is a makeshift solution, but I don't like it, so I'm not developing it for now. Is there a better way to do this?

@RequestMapping("/add")
public Integer adding(@RequestParam("i") Long index,
                      @RequestParam("i2") Long index2,
                      @RequestParam(value="i3", required = false, defaultValue = "0") Long index3,
                      @RequestParam(value="i4", required = false, defaultValue = "0") Long index4,
                      @RequestParam(value="i5", required = false, defaultValue = "0") Long index5,
                      @RequestParam(value="i6", required = false, defaultValue = "0") Long index6
){
    Integer sum = null;


   Integer i1 = productManager.findById(index).get().getCalories();
   Products second = productManager.findById(index2).get();
   Integer i2 = second.getCalories();

   Integer i3,a,b,c;
   if (index3==0){
       i3=0;
   } else {
       Products thrid = productManager.findById(index3).get();
       i3 = thrid.getCalories();
   }
    sum= i1+i2+i3;
    return sum;
}
zlaval :

You can use list as query param.

@RequestMapping("/add")
public Integer adding(@RequestParam("index") List<Long> indicies){...}

The URL will be the following: http://yourhost:port/add?index=1&index=2&index=3 I suggest to use better name to method and url param then add. Maybe sumCalories or something like that.

If you use RDBMS to persist your products (can you give me more detail please?), you can write a query to sum the requiered value:

@Query("select sum(p.calorie) from Products p where p.id in :ids")
Long sumCaloriesByIds(@Param("ids") List<Long> ids);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131684&siteId=1