Advertisement
Guest User

Untitled

a guest
Aug 25th, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. @Entity
  2. @Data
  3. @Table(name = "books")
  4. public class Book {
  5.  
  6.     @JsonBackReference
  7.     @ManyToMany(mappedBy = "books")
  8.     private Set<Author> authors;
  9.    
  10. }
  11. @Table(name = "authors")
  12. @Data
  13. @Entity
  14. public class Author {
  15.    
  16.     @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  17.     @JoinTable(name = "author_book",
  18.                 joinColumns = @JoinColumn(name = "author_id", referencedColumnName = "author_id"),
  19.                 inverseJoinColumns = @JoinColumn(name = "book_id", referencedColumnName = "book_id"))
  20.     @JsonManagedReference
  21.     private Set<Book> books;
  22.  
  23. }
  24. @Slf4j
  25. @Service
  26. @AllArgsConstructor
  27. public class AuthorService {
  28.     private final AuthorRepo authorRepo;
  29.     private final BookRepo bookRepo;
  30.  
  31.     public Author findById(Long id) {
  32.         Author author = authorRepo.findById(id)
  33.                 .orElseThrow(() -> new ResourceNotFoundException("Author not found with id: " + id));
  34.        
  35.         Hibernate.initialize(author.getBooks());
  36.        
  37.         return author;
  38.     }
  39.  
  40.     public Author addBookToAuthor(Long authorId, Long bookId) {
  41.         Author author = authorRepo.findById(authorId)
  42.                 .orElseThrow(() -> new ResourceNotFoundException("Author not found with id: " + authorId));
  43.         Book book = bookRepo.findById(bookId)
  44.                 .orElseThrow(() -> new ResourceNotFoundException("Book not found with id: " + bookId));
  45.  
  46.         Set<Book> books = author.getBooks();
  47.         if (books == null) {
  48.             books = new HashSet<>();
  49.         }
  50.  
  51.         books.add(book);
  52.         author.setBooks(books);
  53.  
  54.         author = authorRepo.save(author);
  55.         authorRepo.flush();
  56.  
  57.         return author;
  58.     }
  59.  
  60. }
  61. @RestController
  62. @RequestMapping("authors")
  63. @AllArgsConstructor
  64. public class AuthorController {
  65.     private final AuthorService authorService;
  66.    
  67.  
  68.     @ResponseStatus(HttpStatus.OK)
  69.     @GetMapping("/{id}")
  70.     public Author findAuthorById(@PathVariable Long id) {
  71.         return authorService.findById(id);
  72.     }
  73.  
  74.     @ResponseStatus(HttpStatus.OK)
  75.     @PutMapping("/{authorId}/AddBook")
  76.     public Author addBookToAuthor(@PathVariable Long authorId, Long bookId) {
  77.         return authorService.addBookToAuthor(authorId, bookId);
  78.     }
  79.  
  80.    
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement