Reading rows.getObject(3) works, but nothing in it says "price". And if someone changes the order of the columns in the SELECT, every number silently points at the wrong value.
JdbcTemplate can give rows that know their column names. db.queryForList(...) returns a List with one Map per row, whose keys are the column names: row.get("price") works, and new HashMap<>(row) copies the whole row into a new map. For example, with a table books:
List<Map<String, Object>> books = db.queryForList("SELECT title, year FROM books");
Map<String, Object> first = books.get(0);
System.out.println(first.get("title")); // Dune
System.out.println(first); // {title=Dune, year=1965}
Since the code no longer depends on the order of the columns, the query can ask for all of them with SELECT *. The products' stock comes along too.
GET / → 200 Welcome to the shop!
GET /products → 200 [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen", "stock": 10},
{"id": 2, "name": "Notebook", "price": 7, "category": "office", "stock": 0},
… 8 products in all …
{"id": 8, "name": "Gift card", "price": 50, "category": null, "stock": 999}]
Your task: make getProducts ask for every column of products with queryForList, loop over its rows, and build each product as a copy of its row instead of reading values by number.
Assignment
Follow the Coding Tutorial to switch the shop to rows as maps and SELECT *.
HintqueryForList already gives each row as a map from column name to value, so new HashMap<>(row) needs no keys from you. The loop's closing brace is already in the editor: you add its first line.
Free plan: 30 tutor messages. PRO is unlimited.
