1
+ package com .youdemy .controller ;
2
+
3
+ import java .util .Optional ;
4
+
5
+ import org .springframework .beans .factory .annotation .Autowired ;
6
+ import org .springframework .dao .EmptyResultDataAccessException ;
7
+ import org .springframework .http .HttpStatus ;
8
+ import org .springframework .http .ResponseEntity ;
9
+ import org .springframework .web .bind .annotation .*;
10
+
11
+ import com .youdemy .model .OrderP ;
12
+ import com .youdemy .service .OrderPService ;
13
+
14
+ @ RestController
15
+ @ RequestMapping ("/api/orders" )
16
+ public class OrderPRestController {
17
+
18
+ @ Autowired
19
+ private OrderPService orderService ;
20
+
21
+ @ GetMapping ("/{id}" )
22
+ public ResponseEntity <OrderP > getOrder (@ PathVariable long id ) {
23
+
24
+ Optional <OrderP > order = orderService .findById (id );
25
+ if (order .isPresent ()) {
26
+ OrderP dbOrder = order .get ();
27
+ return new ResponseEntity <>(dbOrder , HttpStatus .OK );
28
+ }else {
29
+ return new ResponseEntity <>(HttpStatus .NOT_FOUND ); // trying access to not present resource
30
+ }
31
+ }
32
+
33
+ @ PostMapping ("/" )
34
+ @ ResponseStatus (HttpStatus .CREATED )
35
+ public OrderP createBook (@ RequestBody OrderP order ) {
36
+
37
+ orderService .save (order );
38
+
39
+ return order ;
40
+ }
41
+
42
+ @ PutMapping ("/{id}" )
43
+ public ResponseEntity <Optional <OrderP >> replaceOrder (@ PathVariable long id , @ RequestBody OrderP newOrder ) {
44
+ Optional <OrderP > put = orderService .findById (id );
45
+
46
+ if (put != null ) {
47
+ newOrder .setId (id );
48
+ orderService .save (newOrder );
49
+ return ResponseEntity .ok (put );
50
+ } else {
51
+ return ResponseEntity .notFound ().build ();
52
+ }
53
+ }
54
+
55
+ @ DeleteMapping ("/{id}" )
56
+ public ResponseEntity <OrderP > deleteOrder (@ PathVariable long id ) {
57
+
58
+ try {
59
+ orderService .delete (id );
60
+ return new ResponseEntity <>(null , HttpStatus .OK );
61
+
62
+ } catch (EmptyResultDataAccessException e ) {
63
+ return new ResponseEntity <>(null , HttpStatus .NOT_FOUND );
64
+ }
65
+ }
66
+ }
0 commit comments