Skip to content

Instantly share code, notes, and snippets.

@Ikhiloya
Created July 24, 2018 02:46
Show Gist options
  • Select an option

  • Save Ikhiloya/283df830a5aaa5d5a1a4a6be69d3214d to your computer and use it in GitHub Desktop.

Select an option

Save Ikhiloya/283df830a5aaa5d5a1a4a6be69d3214d to your computer and use it in GitHub Desktop.
controller for Author-Book One-To-Many Relationship
package com.loya.onetomanybidirectionaldemo.controller;
import com.loya.onetomanybidirectionaldemo.entity.Author;
import com.loya.onetomanybidirectionaldemo.entity.Book;
import com.loya.onetomanybidirectionaldemo.service.AuthorService;
import com.loya.onetomanybidirectionaldemo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
public class AuthorBookController {
@Autowired
AuthorService authorService;
@Autowired
BookService bookService;
//Author
@RequestMapping(value = "/getAllAuthors", method = RequestMethod.GET)
public List<Author> getAuthors() {
return authorService.getAuthors();
}
@RequestMapping(value = "/author", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Author createAuthor(@RequestBody Author author) {
return authorService.createAuthor(author);
}
@RequestMapping(value = "/getAllBooks", method = RequestMethod.GET)
public List<Book> getBooks() {
return bookService.getAllBooks();
}
//Book
@RequestMapping(value = "/{authorId}/book", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Book createBook(@PathVariable(value = "authorId") Long authorId, @RequestBody Book book) {
return bookService.createBook(authorId, book);
}
@RequestMapping(value = "/book/{bookId}", method = RequestMethod.GET)
public Optional<Book> getBookById(@PathVariable(value = "bookId") Long bookId) {
return bookService.getBookById(bookId);
}
//others omitted for brevity
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment