1
+ package com .kaluzny .web ;
2
+
3
+ import com .kaluzny .domain .Book ;
4
+ import com .kaluzny .domain .BookRepository ;
5
+ import org .springframework .beans .factory .annotation .Autowired ;
6
+ import org .springframework .http .HttpStatus ;
7
+ import org .springframework .http .ResponseEntity ;
8
+ import org .springframework .web .bind .annotation .*;
9
+
10
+ import java .util .Collection ;
11
+
12
+ @ RestController
13
+ @ RequestMapping ("/books" )
14
+ public class BookController {
15
+
16
+ private BookRepository repository ;
17
+
18
+ @ Autowired
19
+ public void setRepository (BookRepository repository ) {
20
+ this .repository = repository ;
21
+ }
22
+
23
+ @ RequestMapping (
24
+ method = RequestMethod .GET )
25
+ public ResponseEntity <Collection <Book >> getAllBooks () {
26
+ return new ResponseEntity <>((Collection <Book >) repository .findAll (), HttpStatus .OK );
27
+ }
28
+
29
+ @ RequestMapping (
30
+ method = RequestMethod .GET ,
31
+ value = "/{id}" )
32
+ public ResponseEntity <Book > getBookWithId (@ PathVariable Long id ) {
33
+ return new ResponseEntity <>(repository .findOne (id ), HttpStatus .OK );
34
+ }
35
+
36
+ @ RequestMapping (
37
+ method = RequestMethod .GET ,
38
+ params = {"name" })
39
+ public ResponseEntity <Collection <Book >> findBookWithName (@ RequestParam (value = "name" ) String name ) {
40
+ return new ResponseEntity <>(repository .findByName (name ), HttpStatus .OK );
41
+ }
42
+
43
+ @ RequestMapping (
44
+ method = RequestMethod .POST )
45
+ public ResponseEntity <?> addBook (@ RequestBody Book book ) {
46
+ return new ResponseEntity <>(repository .save (book ), HttpStatus .CREATED );
47
+ }
48
+
49
+ @ RequestMapping (
50
+ method = RequestMethod .DELETE ,
51
+ value = "/{id}" )
52
+ public void deleteBookWithId (@ PathVariable Long id ) {
53
+ repository .delete (id );
54
+ }
55
+
56
+ @ RequestMapping (
57
+ method = RequestMethod .DELETE )
58
+ public void deleteAllBooks () {
59
+ repository .deleteAll ();
60
+ }
61
+ }
0 commit comments