Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. @Service
  2. @Slf4j
  3. public class BookService {
  4.  
  5. @Autowired
  6. private BookRepository repo;
  7.  
  8. private Mapper mapper;
  9.  
  10. @Autowired
  11. public BookService(BookRepository repo, Mapper mapper) {
  12. this.repo = repo;
  13. this.mapper = mapper;
  14. }
  15.  
  16. public Book create(BookRequest request) {
  17. Assert.notNull(request.getTitle(), "Title can't be null!");
  18. Assert.notNull(request.getAuthor(), "Author can't be null!");
  19. Assert.notNull(request.getGenre(), "Genre can't be null!");
  20.  
  21. BookEntity entity = mapper.map(request, BookEntity.class);
  22. entity = repo.save(entity);
  23. Book book = mapper.map(entity, Book.class);
  24.  
  25. return book;
  26. }
  27.  
  28. public Book getById(UUID id) {
  29. BookEntity entity = repo.findOne(id);
  30. return map(entity);
  31. }
  32.  
  33. public List<Book> get(String title, String author, Genre genre) {
  34. if (title != null && author == null && genre == null) {
  35. return map(repo.findByTitleIgnoreCase(title));
  36. } else if (title != null && author != null && genre == null) {
  37. return map(repo.findByTitleIgnoreCaseAndAuthorIgnoreCase(title,
  38. author));
  39. } else if (title != null && author != null && genre != null) {
  40. return map(
  41. repo.findByTitleIgnoreCaseAndAuthorIgnoreCaseAndGenre(title,
  42. author, genre));
  43. } else if (title == null && author != null && genre == null) {
  44. return map(repo.findByAuthorIgnoreCase(author));
  45. } else if (title == null && author != null && genre != null) {
  46. return map(repo.findByAuthorIgnoreCaseAndGenre(author, genre));
  47. } else if (title != null && author == null && genre != null) {
  48. return map(repo.findByTitleIgnoreCaseAndGenre(title, genre));
  49. } else if (title == null && author == null && genre != null) {
  50. return map(repo.findByGenre(genre));
  51. } else {
  52. throw new InvalidSearchException(
  53. "Specify at least one search critera!");
  54. }
  55. }
  56.  
  57. public void delete(UUID id) {
  58. repo.delete(id);
  59. }
  60.  
  61. public void deleteAll() {
  62. repo.deleteAll();
  63. }
  64.  
  65. private List<Book> map(List<BookEntity> entities) {
  66. if (entities == null || entities.isEmpty()) {
  67. throw new DataNotFoundException(
  68. "No books found with the search criteria!");
  69. }
  70.  
  71. return entities.stream().map(
  72. r -> mapper.map(r, Book.class)).collect(
  73. Collectors.toList());
  74. }
  75.  
  76. private Book map(BookEntity entity) {
  77. if (entity == null) {
  78. throw new InvalidSearchException("Book not found!");
  79. }
  80.  
  81. return mapper.map(entity, Book.class);
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement