AI Hints
Home›Spring Boot Tutorial›CRUD with JpaRepository, Seeding Data and Practice: Books in a Database
Spring Boot · Lesson 54 of 120

Practice: Books in a Database

Your turn.

⏱ 2 min read▶ Video at 1:12:52🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Let's practise with the repository. Prices change, so we need an endpoint to update one.

  • The repository
  • Prices change
  • Update one

Update a price

Your turn. Pause the video, and try this. Add PUT slash books slash id slash price, with a value parameter. Load the book, change its price, save it, and return it. If the book doesn't exist, return four oh four. Here is one solution. Find by id gives an Optional. Map runs only if the book was found. And or else gives the four oh four. Dune now costs seven ninety nine. And book ninety nine is not found.

✍️ Exercise: Update a price

PUT /books/{id}/price?value=7.99 → load the book, setPrice, save, return 200 with it. Missing id → 404.

Show hint

books.findById(id).map(book -> ...).orElse(ResponseEntity.notFound().build())

Show solution
BookController.javajava
@RestController
public class BookController {

    private final BookRepository books;

    public BookController(BookRepository books) { this.books = books; }

    @PutMapping("/books/{id}/price")
    public ResponseEntity<Book> price(@PathVariable Long id, @RequestParam double value) {
        return books.findById(id)
            .map(book -> {
                book.setPrice(value);
                return ResponseEntity.ok(books.save(book));
            })
            .orElse(ResponseEntity.notFound().build());
    }
}
Output
$ curl -X PUT "localhost:8080/books/1/price?value=7.99"
{"id":1,"title":"Dune","author":"Frank Herbert","price":7.99}
$ curl -i -X PUT "localhost:8080/books/99/price?value=5" | head -1
HTTP/1.1 404

What module six taught

A database keeps data safe in tables. H2 runs inside our app, for learning. JPA maps entity classes to tables, using at Entity, and at Id. And repositories give us save, find, and delete, without writing any SQL.

keyvalue
Databasetables, rows, SQL
H2in-memory database
JPA@Entity, @Id, @GeneratedValue
RepositoryJpaRepository<Book, Long>

Summary

Your API now stores books in a real database. That's the end of module six. Next module, queries.

Key takeaways
  • Entities
  • Repositories
  • Seeding
Next up: Derived Query Methods — queries from method names