A list inside your code forgets everything when the app stops. A database keeps data in a file instead. From now on the shop's products live in the file shop.db, in the products table, and Spring's JdbcTemplate lets your app talk to it.
Spring makes a JdbcTemplate once, when the app starts, and passes it to your controller's constructor, which keeps it in a field. Then db.queryForRowSet(...) runs a SQL query and gives its rows. rows.next() moves to the next row (it is false after the last one), and rows.getObject(n) reads the value of the n-th column you asked for, counted from 1. For example, with a table books that has a title and a year:
SqlRowSet rows = db.queryForRowSet("SELECT title, year FROM books");
while (rows.next()) {
System.out.println(rows.getObject(1) + " " + rows.getObject(2));
}
// Dune 1965
// Emma 1815
An API answers with objects whose keys say what each value is, not with bare rows, so each row becomes a Map. A cell that is empty in the database (NULL) arrives in Java as null, and JSON writes it as null too.
GET / → 200 Welcome to the shop!
GET /products → 200 [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"},
{"id": 2, "name": "Notebook", "price": 7, "category": "office"},
… 8 products in all …
{"id": 8, "name": "Gift card", "price": 50, "category": null}]
Your task: give ShopController a JdbcTemplate field db, set by its constructor, and make GET /products read the products from the products table, turning each row into a map with the keys id, name, price and category.
Assignment
Follow the Coding Tutorial to give the controller its database, run the query and turn its rows into the list of products.
Hint
Columns are counted from 1, in the order of your SELECT: rows.getObject(1) is the first column you named. A final field must be set in the constructor, or Java won't compile.
Free plan: 30 tutor messages. PRO is unlimited.
