bizzcuit

BookMapper

Sep 25th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. package com.rewe.exercise.bookstore.book;
  2.  
  3. import com.rewe.exercise.bookstore.author.Author;
  4. import com.rewe.exercise.bookstore.author.AuthorEntity;
  5. import com.rewe.exercise.bookstore.author.AuthorRepository;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import java.util.List;
  9. import java.util.stream.Collectors;
  10.  
  11. @Service
  12. public class BookMapper {
  13.  
  14. private final AuthorRepository authorRepository;
  15.  
  16. public BookMapper(AuthorRepository authorRepository) {
  17. this.authorRepository = authorRepository;
  18. }
  19.  
  20. List<Book> map(List<BookEntity> bookEntities) {
  21. return bookEntities.stream()
  22. .map(this::map)
  23. .collect(Collectors.toList());
  24.  
  25. }
  26.  
  27. Book map(BookEntity bookEntity) {
  28.  
  29. Book book = new Book();
  30. book.setIsbn(bookEntity.getIsbn());
  31. book.setTitle(bookEntity.getTitle());
  32. book.setPublisher(bookEntity.getPublisher());
  33. book.setYear(bookEntity.getYear());
  34. book.setPrice(bookEntity.getPrice());
  35. book.setAvailableQuantity(bookEntity.getAvailableQuantity());
  36. book.setAuthors(bookEntity.getAuthors().stream().map(authorEntity -> {
  37. Author author = new Author();
  38. author.setFirstName(authorEntity.getFirstName());
  39. author.setLastName(authorEntity.getLastName());
  40. return author;
  41. }).collect(Collectors.toList()));
  42. return book;
  43. }
  44.  
  45. List<BookEntity> mapToEntity(List<Book> books) {
  46. return books.stream()
  47. .map(this::map)
  48. .collect(Collectors.toList());
  49.  
  50. }
  51.  
  52. BookEntity map(Book book) {
  53.  
  54. BookEntity bookEntity = new BookEntity();
  55. bookEntity.setIsbn(book.getIsbn());
  56. bookEntity.setTitle(book.getTitle());
  57. bookEntity.setPublisher(book.getPublisher());
  58. bookEntity.setYear(book.getYear());
  59. bookEntity.setPrice(book.getPrice());
  60. bookEntity.setAvailableQuantity(book.getAvailableQuantity());
  61.  
  62.  
  63. book.getAuthors().forEach(author -> {
  64. authorRepository.findByFirstNameAndLastName(author.getFirstName(), author.getLastName())
  65. .ifPresentOrElse(authorEntity -> {
  66. bookEntity.getAuthors().add(authorEntity);
  67. authorEntity.getAuthorBooks().add(bookEntity);
  68. }, () -> {
  69. AuthorEntity authorEntity = new AuthorEntity();
  70. authorEntity.setFirstName(author.getFirstName());
  71. authorEntity.setLastName(author.getLastName());
  72. authorEntity.setAuthorBooks(List.of(bookEntity));
  73. bookEntity.getAuthors().add(authorEntity);
  74. });
  75. });
  76.  
  77.  
  78. return bookEntity;
  79.  
  80. }
  81. }
Add Comment
Please, Sign In to add comment