CRUD with JpaRepository
The API, for real.
Let's rebuild our book API, but this time on a real database. The map disappears. The repository takes its place.
- Our book API again
- No more map
- A real database
Create and read
The controller receives the repository. Find all lists every book. Find by id returns an Optional, and Response Entity dot of turns it into two hundred, or four oh four. Save inserts the new book, and returns it with its id. Run it. Each POST returns the saved book, with an id from the database. Book two is Circe. And book nine is not found.
@RestController
@RequestMapping("/books")
public class BookController {
private final BookRepository books;
public BookController(BookRepository books) { this.books = books; }
@GetMapping
public List<Book> all() { return books.findAll(); }
@GetMapping("/{id}")
public ResponseEntity<Book> one(@PathVariable Long id) {
return ResponseEntity.of(books.findById(id));
}
@PostMapping
public Book add(@RequestBody Book book) { return books.save(book); }
}$ curl --json '{"title":"Dune","author":"Herbert","price":9.99}' localhost:8080/books
{"id":1,"title":"Dune","author":"Herbert","price":9.99}
$ curl --json '{"title":"Circe","author":"Miller","price":10.99}' localhost:8080/books
{"id":2,"title":"Circe","author":"Miller","price":10.99}
$ curl localhost:8080/books/2
{"id":2,"title":"Circe","author":"Miller","price":10.99}
$ curl -i localhost:8080/books/9 | head -1
HTTP/1.1 404Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
}Also uses _curl.sh
curl --json '{"title":"Dune","author":"Herbert","price":9.99}' localhost:8080/books
curl --json '{"title":"Circe","author":"Miller","price":10.99}' localhost:8080/books
curl localhost:8080/books/2
curl -i localhost:8080/books/9 | head -1Delete
This time, the database starts with five books, which we'll explain next lesson. Exists by id checks first, so a missing book gives four oh four. Otherwise, delete by id removes it, and we return two oh four. Run it. The first delete works. The second finds nothing. And four books remain.
@RestController
@RequestMapping("/books")
public class BookController {
private final BookRepository books;
public BookController(BookRepository books) { this.books = books; }
@GetMapping
public List<Book> all() { return books.findAll(); }
@DeleteMapping("/{id}")
public ResponseEntity<Void> remove(@PathVariable Long id) {
if (!books.existsById(id)) return ResponseEntity.notFound().build();
books.deleteById(id);
return ResponseEntity.noContent().build();
}
}$ curl -i -X DELETE localhost:8080/books/1 | head -1
HTTP/1.1 204
$ curl -i -X DELETE localhost:8080/books/1 | head -1
HTTP/1.1 404
$ curl localhost:8080/books
[
{"id":2,"title":"The Hobbit","author":"J.R.R. Tolkien","price":8.99},
{"id":3,"title":"Circe","author":"Madeline Miller","price":10.99},
{"id":4,"title":"Children of Dune","author":"Frank Herbert","price":8.49},
{"id":5,"title":"Song of Achilles","author":"Madeline Miller","price":9.49}
]Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
}Also uses data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueAlso uses _curl.sh
curl -i -X DELETE localhost:8080/books/1 | head -1
curl -i -X DELETE localhost:8080/books/1 | head -1
curl localhost:8080/booksSame API, real storage
The URLs, and the JSON, are exactly the same as before. Only the storage changed. That's the power of layers. The client never knows, or cares, where the data lives.
| key | value |
|---|---|
| URLs | unchanged |
| JSON | unchanged |
| Storage | map → database |
| Client | doesn't notice |
Summary
The repository replaces the map. Find all, find by id, save, and delete by id give us a full CRUD API, on a real database. Next, seeding data.
Key takeaways- findAll / findById
- save
- deleteById