Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Entity
- @Data
- @Table(name = "books")
- public class Book {
- @JsonBackReference
- @ManyToMany(mappedBy = "books")
- private Set<Author> authors;
- }
- @Table(name = "authors")
- @Data
- @Entity
- public class Author {
- @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
- @JoinTable(name = "author_book",
- joinColumns = @JoinColumn(name = "author_id", referencedColumnName = "author_id"),
- inverseJoinColumns = @JoinColumn(name = "book_id", referencedColumnName = "book_id"))
- @JsonManagedReference
- private Set<Book> books;
- }
- @Slf4j
- @Service
- @AllArgsConstructor
- public class AuthorService {
- private final AuthorRepo authorRepo;
- private final BookRepo bookRepo;
- public Author findById(Long id) {
- Author author = authorRepo.findById(id)
- .orElseThrow(() -> new ResourceNotFoundException("Author not found with id: " + id));
- Hibernate.initialize(author.getBooks());
- return author;
- }
- public Author addBookToAuthor(Long authorId, Long bookId) {
- Author author = authorRepo.findById(authorId)
- .orElseThrow(() -> new ResourceNotFoundException("Author not found with id: " + authorId));
- Book book = bookRepo.findById(bookId)
- .orElseThrow(() -> new ResourceNotFoundException("Book not found with id: " + bookId));
- Set<Book> books = author.getBooks();
- if (books == null) {
- books = new HashSet<>();
- }
- books.add(book);
- author.setBooks(books);
- author = authorRepo.save(author);
- authorRepo.flush();
- return author;
- }
- }
- @RestController
- @RequestMapping("authors")
- @AllArgsConstructor
- public class AuthorController {
- private final AuthorService authorService;
- @ResponseStatus(HttpStatus.OK)
- @GetMapping("/{id}")
- public Author findAuthorById(@PathVariable Long id) {
- return authorService.findById(id);
- }
- @ResponseStatus(HttpStatus.OK)
- @PutMapping("/{authorId}/AddBook")
- public Author addBookToAuthor(@PathVariable Long authorId, Long bookId) {
- return authorService.addBookToAuthor(authorId, bookId);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement