Java tutorial
// Copyright 2014 Bruno M. Custdio // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.brunomcustodio.dojo.springboot; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RequestMapping("/books") @RestController public class BookServiceController { @Autowired private BookRepository repository; @RequestMapping(value = "/", method = RequestMethod.GET) public Iterable<Book> findBooks() { return repository.findAll(); } @RequestMapping(value = "/", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public Book createBook(@RequestBody @Valid Book book) { return repository.save(book); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteBook(@PathVariable("id") int id) { try { repository.delete(id); } catch (EmptyResultDataAccessException ex) { throw new BookNotFoundException(ex); } } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Book findBook(@PathVariable("id") int id) { Book result = repository.findOne(id); if (result != null) { return result; } else { throw new BookNotFoundException(); } } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public Book updateBook(@PathVariable("id") int id, @RequestBody @Valid Book book) { Book target = repository.findOne(id); if (target != null) { book.setId(id); return repository.save(book); } else { throw new BookNotFoundException(); } } }