Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

java - Add one row from table to table

I'm making pet app(shop) and i'm confused about one thing - i don't understand how to add product to shopping cart. I have 2 tables - products and cart, they have same fields. Here is my code with 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>

Here is my controller, what is supposed to save one row from products to cart:

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

and query(i know that it copies all products to cart, but its only for example):

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

My question is - how can i copy just one row(one product) in this case? How i can separate product id for adding to cart? should it be done in controller or maybe in sql query?I'm just missing something simple((

question from:https://stackoverflow.com/questions/65853026/add-one-row-from-table-to-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Seems like your query is selecting all columns from products with the * sign. What you can do is try limiting the query result by using limit 1 after products.

Also if you want to extract rows with certain product id, you can try simple where keyword that specify conditions. e.g. where product_id = your_desired_id it should return all rows that match your requirement id.

If you want to actually separate the entire product_id column from your result to cart. Why not try select [input_here_columns_besides_product_id] from products?

Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...