为了账号安全,请及时绑定邮箱和手机立即绑定

通过 Rest 服务从数据库中添加许多(未指定数量)对象的方法

通过 Rest 服务从数据库中添加许多(未指定数量)对象的方法

蛊毒传说 2023-02-16 16:59:03
我正在尝试编写自己的应用程序。它应该提供带有参数的添加食品,我已经完成了,进一步的目的是总结添加产品的所有属性,与每日余额进行比较等。我对将产品与一顿饭联系起来的概念有疑问。我想知道是否有一些漂亮的替代函数可以使用特定数量的(可选)参数,女巫是功能的一定限制。这是一个临时解决方案,但我不喜欢它,所以我暂时不开发它。有一个更好的方法吗?@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;}
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

您可以使用列表作为查询参数。

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

URL 如下:http://yourhost:port/add?index=1&index=2&index=3 I suggest to use better name to method and url param then add。也许sumCalories或类似的东西。

如果你使用 RDBMS 来保存你的产品(你能给我更多的细节吗?),你可以写一个查询来求和所需的值:

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


查看完整回答
反对 回复 2023-02-16
  • 1 回答
  • 0 关注
  • 71 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信