java—从一个表到另一个表添加一行

nfg76nw0  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(339)

我正在制作宠物应用程序(商店),我对一件事感到困惑-我不知道如何将产品添加到购物车。我有两个表-产品和购物车,他们有相同的领域。这是我和thymeleaf的代码:

  1. <tbody>
  2. <tr th:each="products : ${products}">
  3. <td th:text="${products.name}"></td>
  4. <td th:text="${products.price}"></td>
  5. <td th:text="${products.quantity}"></td>
  6. <td th:text="${products.serial}"></td>
  7. <td> <p><a href="/product-add" class="btn btn-primary">Add to cart</a></p>
  8. </td>
  9. </tr>
  10. </tbody>

这是我的控制器,应该将一行从产品保存到购物车:

  1. @RequestMapping("product-add")
  2. public String addToCart (Model model) {
  3. model.addAttribute("selection", cartRepository.selection());
  4. return "redirect:/products";
  5. }

和查询(我知道它会将所有产品复制到购物车,但仅举个例子):

  1. @Query(value = "insert into cart(select * from products )", nativeQuery = true)
  2. List<Cart> selection();

我的问题是-在这种情况下,如何只复制一行(一个产品)?如何分离产品id以添加到购物车?它应该在controller中完成还是在sql查询中完成?我只是缺少一些简单的东西((

mwg9r5ms

mwg9r5ms1#

似乎您的查询正在从具有 * 签字。您可以尝试使用 limit 1 售后服务。
另外,如果要提取具有特定产品标识的行,可以尝试使用simple where 指定条件的关键字。例如 where product_id = your_desired_id 它应该返回与您的需求id匹配的所有行。
如果您真的想将整个product\u id列从您的购物车结果中分离出来。为什么不试试 select [input_here_columns_besides_product_id] from products ?
祝你好运!

相关问题