1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| package com.sanhaoxuesheng.demo.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid;
import com.sanhaoxuesheng.demo.exception.ResourceNotFoundException; import com.sanhaoxuesheng.demo.model.Note; import com.sanhaoxuesheng.demo.repository.NoteRepository;
import java.util.List;
@RestController @RequestMapping("/api") public class NoteController {
@Autowired NoteRepository noteRepository;
@GetMapping("/notes") public List<Note> getAllNotes() {
return noteRepository.findAll(); }
@PostMapping("/notes") public Note createNote(@Valid @RequestBody Note note) { return noteRepository.save(note); }
@GetMapping("/notes/{id}") public Note getNoteById(@PathVariable(value = "id") Long noteId) {
return noteRepository.findById(noteId).orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId)); }
@PutMapping("/notes/{id}") public Note updateNote(@PathVariable(value = "id") Long noteId, @Valid @RequestBody Note noteDetails) { Note note = noteRepository.findById(noteId) .orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId)); note.setTitle(noteDetails.getTitle()); note.setContent(noteDetails.getContent()); Note updatedNote = noteRepository.save(note); return updatedNote; }
@DeleteMapping("/notes/{id}") public ResponseEntity<Object> deleteNote(@PathVariable(value = "id") Long noteId) {
Note note = noteRepository.findById(noteId) .orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId)); noteRepository.delete(note);
return ResponseEntity.ok().build(); } }
|