Start learning free

LESSON 81 OF 173 · BACKEND: APIS WITH A DATABASE

A Small Query Helper in Java

Practice

Look at your routes. Almost every one runs db.queryForList(...), copies the rows with new HashMap<>(row), or checks rows.isEmpty() and takes rows.get(0). Every route types the same moves again. A helper is a small method that makes those moves once, so each route gets its rows in one line.

Any number of values: a parameter written with ... (varargs) takes any number of values, and the method gets them as one array. For example:

int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) {
        total = total + n;
    }
    return total;
}

sum(2, 3, 4);   // numbers is {2, 3, 4}: 9
sum();          // numbers is an empty array: 0

Your helper, query(String sql, Object... params), runs the SQL with its values and answers a list of maps. Its partner queryOne, with the same parameters, answers only the first map, or null when no row matched. The routes must answer just as before:

GET /products?category=kitchen  →  200  {"products": [{"id": 1, "name": "Mug", …}, {"id": 6, "name": "Teapot", …}], "total": 2, "next_page": null}
GET /products?name=Sofa         →  200  {"products": [], "total": 0, "next_page": null}
GET /products/3                 →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home", "stock": 1, "discount": 0}
GET /products/99                →  404  {"error": "Product not found"}

Your task: below migrate(), write the helper query: it runs the SQL with its params and answers a list of maps. Then fill in queryOne, whose header is already there: the first map, or null. Make getProducts get its page from query and getProduct its row from queryOne, in one line each.


Assignment
Follow the Coding Tutorial to write query and queryOne and use them in getProducts and getProduct.


Hint
getProducts keeps its values in a List: pass params.toArray(), because a List would arrive as one single value. And result.get(0) on an empty list throws an IndexOutOfBoundsException, so return null first when result is empty.


STEP 1 OF 12
    Ctrl + Enter to check

    Db Query Helper 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