POST

Handle a POST request with @PostMapping and @RequestBody, insert the new category with a JdbcTemplate and return it with its generated id and a 201 status.

Journeyman · Spring Boot · REST API · Updated

Adding or inserting a new record should be done through a POST request. When a client POSTs a new record - they must include the information that will be inserted in the body.

A POST request carries a header (POST /categories) and a body with the new category's name and description

The server is responsible for saving that data. The server should respond with the full resource, including the new ID that was generated

The server answers 201 (created), and the body is the saved category with its new categoryId, 10

POST Request - Client

In Insomnia, this is your Add Snacks request from Insomnia: POST, with the new category as JSON on its Body tab:

POST {{ _.base_url }}/api/categories
{
  "categoryName": "Snacks",
  "description": "Chips, nuts and pretzels"
}

POST Request - Server

When a client makes a request, just like a GET the server directs the request to a Controller. The method responsible for handling the request must be marked with a @PostMapping annotation to handle the request. The body of the request is passed as a method parameter using the @RequestBody annotation. The @ResponseStatus annotation specifies the status code that will be returned (HttpStatus.CREATED returns a status of 201)

@PostMapping(path="/api/categories")
@ResponseStatus(value = HttpStatus.CREATED)
public Category addCategory (@RequestBody Category category)
{
  //The insert method of the DAO should return
  // a Category object with the new ID that was generated
  Category newCategory = categoryDao.insert(category);

  // return the new category, with its id
  return newCategory;
}

DAO Logic

The DAO is not only responsible for inserting the new record, but it must also return the new ID that was generated by the database.

JDBC runs SQL through Statement and PreparedStatement objects. By default, a statement doesn't hand back the id the database generated. To get it, we create the PreparedStatement ourselves with Statement.RETURN_GENERATED_KEYS, and a KeyHolder collects the new id.

public Category insert(Category category)
{
    String sql = """
            INSERT INTO categories (category_name, description)
            VALUES (?,?)
            """;

    // insert a new record and retrieve the generated id
    KeyHolder keyHolder = new GeneratedKeyHolder();

    jdbcTemplate.update(connection -> {
        // we have to define the PreparedStatement directly
        PreparedStatement statement = connection.prepareStatement(
                            sql
                            , Statement.RETURN_GENERATED_KEYS);

        statement.setString(1, category.getCategoryName());
        statement.setString(2, category.getDescription());

        return statement;
    }, keyHolder);

    // get the new id from the keyHolder
    int newId = keyHolder.getKey().intValue();

    // read the inserted row back, so the caller gets every column
    return getCategoryById(newId);
}

POST Response - Client

Add the method to your controller and the insert method to your DAO, run the app again, and send Add Snacks. The 405 Method Not Allowed from Insomnia: POST is now 201 Created, with the saved category and its new id.

Insomnia shows 201 Created and the saved category, now with categoryId 10

Cheat sheets