@RestController @RequestMapping("/api/books") public class BookController { @Autowired private BookService bookService; @GetMapping public List<Book> getAllBooks() { return bookService.getAllBooks(); } @GetMapping("/{id}") public Book getBookById(@PathVariable Long id) { return bookService.getBookById(id); } @PostMapping public Book createBook(@RequestBody Book book) { return bookService.createBook(book); } @PutMapping("/{id}") public Book updateBook(@PathVariable Long id, @RequestBody Book book) { book.setId(id); return bookService.updateBook(book); } @DeleteMapping("/{id}") public void deleteBook(@PathVariable Long id) { bookService.deleteBook(id); } }
Run the application using your preferred IDE or by executing the following command:
Add the following dependencies to your pom.xml file (if you're using Maven) or your build.gradle file (if you're using Gradle): spring boot in action cracked
Create a Book model:
Create a BookRepository interface:
Create a BookController class:
mvn spring-boot:run
public interface BookRepository extends JpaRepository<Book, Long> { }
@Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; // Getters and Setters } @GetMapping public List<