Start learning free

LESSON 70 OF 173 · BACKEND: APIS WITH A DATABASE

Add a Product (INSERT) in Java

Practice

Your shop reads its products from shop.db. Now clients can add one: they send a POST to /products, the same path as the list, with the new product in the JSON body. A @PostMapping method reads that body with @RequestBody Map<String, Object> data and saves it with an INSERT statement.

Here is an INSERT on another table, a list of newsletter subscribers:

List<Map<String, Object>> rows = db.queryForList(
    "INSERT INTO subscribers (email) VALUES (?) RETURNING id", "sam@example.com");
System.out.println(rows.get(0).get("id"));   // the id the database chose for the new row

Three things matter. Each ? takes one value, in order, so whatever text the client sends stays a value and never becomes SQL. You leave the id out: the database picks the next free number, and RETURNING id makes the INSERT answer it as a row. And you don't call commit: JdbcTemplate commits each statement as soon as it runs, so the new row is saved for good.

Starting from the shop's 8 products, your code must answer:

POST /products  {"name": "Vase", "price": 18, "category": "home"}  →  201  {"id": 9}
GET /products/9  →  200  {"id": 9, "name": "Vase", "price": 18, "category": "home", "stock": 0}
POST /products  {"name": "Candle", "price": 6}  →  201  {"id": 10}
GET /products?max_price=6  →  200  [{"id": 4, "name": "Pen", …}, {"id": 10, "name": "Candle", "price": 6, "category": null, "stock": 0}]

Your task: add the route POST /products. Read the body, insert the name, the price and the category (which may be missing) with ? placeholders, and answer the new id with the status 201.


Assignment
Follow the Coding Tutorial to add the addProduct method, which saves a new product in the database.


Hint
Read the category with data.get("category"): the Candle has none, and null is stored as NULL. Wrap the answer in ResponseEntity.status(201).body(...) to set the status.


STEP 1 OF 6
    Ctrl + Enter to check

    Db Insert in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free