|
| 1 | +package org.baeldung.web; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +import org.baeldung.persistence.model.Book; |
| 6 | +import org.baeldung.persistence.repo.BookRepository; |
| 7 | +import org.baeldung.web.exception.BookIdMismatchException; |
| 8 | +import org.baeldung.web.exception.BookNotFoundException; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.http.HttpStatus; |
| 11 | +import org.springframework.web.bind.annotation.DeleteMapping; |
| 12 | +import org.springframework.web.bind.annotation.GetMapping; |
| 13 | +import org.springframework.web.bind.annotation.PathVariable; |
| 14 | +import org.springframework.web.bind.annotation.PostMapping; |
| 15 | +import org.springframework.web.bind.annotation.PutMapping; |
| 16 | +import org.springframework.web.bind.annotation.RequestBody; |
| 17 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 18 | +import org.springframework.web.bind.annotation.ResponseStatus; |
| 19 | +import org.springframework.web.bind.annotation.RestController; |
| 20 | + |
| 21 | +@RestController |
| 22 | +@RequestMapping("/api/books") |
| 23 | +public class BookController { |
| 24 | + |
| 25 | + @Autowired |
| 26 | + private BookRepository bookRepository; |
| 27 | + |
| 28 | + @GetMapping |
| 29 | + public Iterable<Book> findAll() { |
| 30 | + return bookRepository.findAll(); |
| 31 | + } |
| 32 | + |
| 33 | + @GetMapping("/title/{bookTitle}") |
| 34 | + public List<Book> findByTitle(@PathVariable String bookTitle) { |
| 35 | + return bookRepository.findByTitle(bookTitle); |
| 36 | + } |
| 37 | + |
| 38 | + @GetMapping("/{id}") |
| 39 | + public Book findOne(@PathVariable Long id) { |
| 40 | + final Book book = bookRepository.findOne(id); |
| 41 | + if (book == null) { |
| 42 | + throw new BookNotFoundException(); |
| 43 | + } |
| 44 | + return book; |
| 45 | + } |
| 46 | + |
| 47 | + @PostMapping |
| 48 | + @ResponseStatus(HttpStatus.CREATED) |
| 49 | + public Book create(@RequestBody Book book) { |
| 50 | + return bookRepository.save(book); |
| 51 | + } |
| 52 | + |
| 53 | + @DeleteMapping("/{id}") |
| 54 | + public void delete(@PathVariable Long id) { |
| 55 | + final Book book = bookRepository.findOne(id); |
| 56 | + if (book == null) { |
| 57 | + throw new BookNotFoundException(); |
| 58 | + } |
| 59 | + bookRepository.delete(id); |
| 60 | + } |
| 61 | + |
| 62 | + @PutMapping("/{id}") |
| 63 | + public Book updateBook(@RequestBody Book book, @PathVariable Long id) { |
| 64 | + if (book.getId() != id) { |
| 65 | + throw new BookIdMismatchException(); |
| 66 | + } |
| 67 | + final Book old = bookRepository.findOne(id); |
| 68 | + if (old == null) { |
| 69 | + throw new BookNotFoundException(); |
| 70 | + } |
| 71 | + return bookRepository.save(book); |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments