Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.rewe.exercise.bookstore.book;
- import com.rewe.exercise.bookstore.author.Author;
- import com.rewe.exercise.bookstore.author.AuthorEntity;
- import com.rewe.exercise.bookstore.author.AuthorRepository;
- import org.springframework.stereotype.Service;
- import java.util.List;
- import java.util.stream.Collectors;
- @Service
- public class BookMapper {
- private final AuthorRepository authorRepository;
- public BookMapper(AuthorRepository authorRepository) {
- this.authorRepository = authorRepository;
- }
- List<Book> map(List<BookEntity> bookEntities) {
- return bookEntities.stream()
- .map(this::map)
- .collect(Collectors.toList());
- }
- Book map(BookEntity bookEntity) {
- Book book = new Book();
- book.setIsbn(bookEntity.getIsbn());
- book.setTitle(bookEntity.getTitle());
- book.setPublisher(bookEntity.getPublisher());
- book.setYear(bookEntity.getYear());
- book.setPrice(bookEntity.getPrice());
- book.setAvailableQuantity(bookEntity.getAvailableQuantity());
- book.setAuthors(bookEntity.getAuthors().stream().map(authorEntity -> {
- Author author = new Author();
- author.setFirstName(authorEntity.getFirstName());
- author.setLastName(authorEntity.getLastName());
- return author;
- }).collect(Collectors.toList()));
- return book;
- }
- List<BookEntity> mapToEntity(List<Book> books) {
- return books.stream()
- .map(this::map)
- .collect(Collectors.toList());
- }
- BookEntity map(Book book) {
- BookEntity bookEntity = new BookEntity();
- bookEntity.setIsbn(book.getIsbn());
- bookEntity.setTitle(book.getTitle());
- bookEntity.setPublisher(book.getPublisher());
- bookEntity.setYear(book.getYear());
- bookEntity.setPrice(book.getPrice());
- bookEntity.setAvailableQuantity(book.getAvailableQuantity());
- book.getAuthors().forEach(author -> {
- authorRepository.findByFirstNameAndLastName(author.getFirstName(), author.getLastName())
- .ifPresentOrElse(authorEntity -> {
- bookEntity.getAuthors().add(authorEntity);
- authorEntity.getAuthorBooks().add(bookEntity);
- }, () -> {
- AuthorEntity authorEntity = new AuthorEntity();
- authorEntity.setFirstName(author.getFirstName());
- authorEntity.setLastName(author.getLastName());
- authorEntity.setAuthorBooks(List.of(bookEntity));
- bookEntity.getAuthors().add(authorEntity);
- });
- });
- return bookEntity;
- }
- }
Add Comment
Please, Sign In to add comment