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

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

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

<tbody>
            <tr th:each="products : ${products}">
                <td th:text="${products.name}"></td>
                <td th:text="${products.price}"></td>
                <td th:text="${products.quantity}"></td>
                <td th:text="${products.serial}"></td>
                <td>    <p><a href="/product-add" class="btn btn-primary">Add to cart</a></p>
                </td>

            </tr>
            </tbody>

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

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

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

@Query(value = "insert into cart(select * from products )", nativeQuery = true)
    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 ?
祝你好运!

相关问题