lab3 it works. finally

This commit is contained in:
Zakharov_Rostislav 2024-04-19 15:43:53 +04:00
parent 264c14bba8
commit 928639bd98
14 changed files with 256 additions and 76 deletions

View File

@ -54,21 +54,17 @@ public class LibraryApplication implements CommandLineRunner {
log.info("Create default authors values");
final var author1 = authorService.create(new AuthorEntity("author1"));
final var author2 = authorService.create(new AuthorEntity("author2"));
final List<AuthorEntity> list1 = new ArrayList<>();
final List<AuthorEntity> list2 = new ArrayList<>();
final List<AuthorEntity> list3 = new ArrayList<>();
list1.add(author1);
list2.add(author2);
list3.add(author1);
list3.add(author2);
log.info("Create default books values");
final var book1 = bookService.create(new BookEntity("book1", type1, list1));
final var book2 = bookService.create(new BookEntity("book2", type1, list2));
final var book3 = bookService.create(new BookEntity("book3", type2, list3));
final var book1 = bookService.create(new BookEntity("book1", type1));
final var book2 = bookService.create(new BookEntity("book2", type1));
final var book3 = bookService.create(new BookEntity("book3", type2));
final var book4 = bookService.create(new BookEntity("book4", type2));
authorService.addBook(author1.getId(), book1.getId());
authorService.addBook(author2.getId(), book2.getId());
authorService.addBook(author1.getId(), book3.getId());
authorService.addBook(author2.getId(), book3.getId());
log.info("Create default users values");
final var user1 = userService.create(new UserEntity("user1", "123"));

View File

@ -15,10 +15,11 @@ import org.springframework.web.bind.annotation.RestController;
import com.ip.library.core.configuration.Constants;
import com.ip.library.authors.model.AuthorEntity;
import com.ip.library.authors.service.AuthorService;
import com.ip.library.books.api.BookDto;
import com.ip.library.books.model.BookEntity;
import com.ip.library.books.service.BookService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.RequestParam;
@RestController
@ -26,11 +27,20 @@ import org.springframework.web.bind.annotation.RequestParam;
public class AuthorController {
private final AuthorService authorService;
private final ModelMapper modelMapper;
private final BookService bookService;
public AuthorController(AuthorService authorService, ModelMapper modelMapper) {
public AuthorController(AuthorService authorService, ModelMapper modelMapper, BookService bookService) {
this.authorService = authorService;
this.modelMapper = modelMapper;
this.bookService = bookService;
}
private BookDto toBookDto (BookEntity entity) {
BookDto bookDto = modelMapper.map(entity, BookDto.class);
bookDto.setAuthorId(bookService.getBookAuthors(
entity.getId()).stream().map(x -> x.getId()).toList());
return bookDto;
}
private AuthorDto toDto(AuthorEntity entity) {
return modelMapper.map(entity, AuthorDto.class);
@ -66,8 +76,8 @@ public class AuthorController {
}
@GetMapping("/{id}/books")
public List<BookEntity> getAuthorBooks(@PathVariable(name = "id") Long id) {
return authorService.getAuthorBooks(id);
public List<BookDto> getAuthorBooks(@PathVariable(name = "id") Long id) {
return authorService.getAuthorBooks(id).stream().map(this::toBookDto).toList();
}
}

View File

@ -4,6 +4,7 @@ import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import com.ip.library.authors_books.model.AuthorsBooksEntity;
import com.ip.library.books.model.BookEntity;
import com.ip.library.core.model.BaseEntity;
@ -13,6 +14,8 @@ import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@ -20,13 +23,9 @@ import jakarta.persistence.Table;
public class AuthorEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 20)
private String name;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "authors_books",
joinColumns = { @JoinColumn(name = "author_id", nullable = false) },
inverseJoinColumns = { @JoinColumn(name = "book_id", nullable = false) }
)
private Set<BookEntity> books = new HashSet<>();
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id ASC")
private Set<AuthorsBooksEntity> authorsBooks = new HashSet<>();
public AuthorEntity() {
super();
@ -44,12 +43,20 @@ public class AuthorEntity extends BaseEntity {
this.name = name;
}
public Set<BookEntity> getBooks() {
return books;
public Set<AuthorsBooksEntity> getAuthorsBooks() {
return authorsBooks;
}
public void setBooks(Set<BookEntity> books) {
this.books = books;
public void setBooks(Set<AuthorsBooksEntity> authorsBooks) {
this.authorsBooks = authorsBooks;
}
public boolean addBook(BookEntity book) {
AuthorsBooksEntity entity = new AuthorsBooksEntity(this, book);
boolean result = authorsBooks.add(entity);
if (!book.getAuthorsBooks().contains(entity))
book.getAuthorsBooks().add(entity);
return result;
}
@Override

View File

@ -15,10 +15,10 @@ public interface AuthorRepository extends
PagingAndSortingRepository<AuthorEntity, Long> {
Optional<AuthorEntity> findByNameIgnoreCase(String name);
@Query(
"select a.books " +
"from AuthorEntity a, BookEntity b " +
"where a.id = ?1 " +
"order by b.id"
"select ab.book " +
"from AuthorsBooksEntity ab " +
"where ab.author.id = ?1 " +
"order by ab.book.id"
)
List<BookEntity> getAuthorBooks(Long authorId);
}

View File

@ -10,13 +10,16 @@ import com.ip.library.core.error.NotFoundException;
import com.ip.library.authors.model.AuthorEntity;
import com.ip.library.authors.repository.AuthorRepository;
import com.ip.library.books.model.BookEntity;
import com.ip.library.books.service.BookService;
@Service
public class AuthorService {
private final AuthorRepository repository;
private final BookService bookService;
public AuthorService(AuthorRepository repository) {
public AuthorService(AuthorRepository repository, BookService bookService) {
this.repository = repository;
this.bookService = bookService;
}
private void checkNameUniqueness(String name) {
@ -69,4 +72,11 @@ public class AuthorService {
public List<BookEntity> getAuthorBooks(long authorId) {
return repository.getAuthorBooks(authorId);
}
@Transactional
public boolean addBook(long authorId, long bookId) {
final AuthorEntity existsAuthor = get(authorId);
final BookEntity book = bookService.get(bookId);
return existsAuthor.addBook(book);
}
}

View File

@ -0,0 +1,81 @@
package com.ip.library.authors_books.model;
import java.util.Objects;
import com.ip.library.authors.model.AuthorEntity;
import com.ip.library.books.model.BookEntity;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.MapsId;
import jakarta.persistence.Table;
@Entity
@Table(name = "authors_books")
public class AuthorsBooksEntity {
@EmbeddedId
private AuthorsBooksId id = new AuthorsBooksId();
@ManyToOne
@MapsId("authorId")
@JoinColumn(name = "author_id")
private AuthorEntity author;
@ManyToOne
@MapsId("bookId")
@JoinColumn(name = "book_id")
private BookEntity book;
public AuthorsBooksEntity() {}
public AuthorsBooksEntity(AuthorEntity author, BookEntity book) {
this.author = author;
this.book = book;
}
public void setId(AuthorsBooksId id) {
this.id = id;
}
public AuthorsBooksId getId() {
return id;
}
public void setAuthor(AuthorEntity author) {
this.author = author;
if (!author.getAuthorsBooks().contains(this))
author.getAuthorsBooks().add(this);
}
public AuthorEntity getAuthor() {
return author;
}
public void setBook(BookEntity book) {
this.book = book;
if (!book.getAuthorsBooks().contains(this))
book.getAuthorsBooks().add(this);
}
public BookEntity getBook() {
return book;
}
@Override
public int hashCode() {
return Objects.hash(id, author.getId(), book.getId());
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final AuthorsBooksEntity other = (AuthorsBooksEntity) obj;
return
Objects.equals(other.getId(), id) &&
Objects.equals(other.getAuthor().getId(), author.getId()) &&
Objects.equals(other.getBook().getId(), book.getId());
}
}

View File

@ -0,0 +1,55 @@
package com.ip.library.authors_books.model;
import java.util.Objects;
import java.util.Optional;
import jakarta.persistence.Embeddable;
@Embeddable
public class AuthorsBooksId {
private Long authorId;
private Long bookId;
public AuthorsBooksId() {}
public AuthorsBooksId(Long authorId, Long bookId) {
this.authorId = authorId;
this.bookId = bookId;
}
public Long getAuthorId() {
return authorId;
}
public void setAuthorId(Long authorId) {
this.authorId = authorId;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
@Override
public int hashCode() {
return Objects.hash(
Optional.ofNullable(authorId).orElse(-1L),
Optional.ofNullable(bookId).orElse(-1L)
);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
AuthorsBooksId other = (AuthorsBooksId) obj;
return
Objects.equals(other.authorId, authorId) &&
Objects.equals(other.bookId, bookId);
}
}

View File

@ -29,22 +29,24 @@ public class BookController {
private final AuthorService authorService;
private final ModelMapper modelMapper;
public BookController(BookService itemService, TypeService typeService,
public BookController(BookService bookService, TypeService typeService,
AuthorService authorService, ModelMapper modelMapper) {
this.bookService = itemService;
this.bookService = bookService;
this.typeService = typeService;
this.authorService = authorService;
this.modelMapper = modelMapper;
}
private BookDto toDto(BookEntity entity) {
return modelMapper.map(entity, BookDto.class);
}
private BookDto toBookDto (BookEntity entity) {
BookDto bookDto = modelMapper.map(entity, BookDto.class);
bookDto.setAuthorId(bookService.getBookAuthors(
entity.getId()).stream().map(x -> x.getId()).toList());
return bookDto;
}
private BookEntity toEntity(BookDto dto) {
final BookEntity entity = modelMapper.map(dto, BookEntity.class);
entity.setType(typeService.get(dto.getTypeId()));
entity.setAuthors(dto.getAuthorsId().stream().map(authorService::get).toList());
return entity;
}
@ -53,27 +55,27 @@ public class BookController {
@RequestParam(name = "typeId", defaultValue = "-1") Long typeId,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return bookService.getAll(typeId).stream().map(this::toDto).toList();
return bookService.getAll(typeId).stream().map(this::toBookDto).toList();
}
@GetMapping("/{id}")
public BookDto get(@PathVariable(name = "id") Long id) {
return toDto(bookService.get(id));
return toBookDto(bookService.get(id));
}
@PostMapping
public BookDto create(@RequestBody @Valid BookDto dto) {
return toDto(bookService.create(toEntity(dto)));
return toBookDto(bookService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public BookDto update(@PathVariable(name = "id") Long id, @RequestBody BookDto dto) {
return toDto(bookService.update(id, toEntity(dto)));
return toBookDto(bookService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public BookDto delete(@PathVariable(name = "id") Long id) {
return toDto(bookService.delete(id));
return toBookDto(bookService.delete(id));
}
@GetMapping("/{bookId}/users/number")

View File

@ -7,12 +7,12 @@ import java.util.Objects;
import java.util.Set;
import com.ip.library.core.model.BaseEntity;
import com.ip.library.favorites.model.FavoriteEntity;
import com.ip.library.types.model.TypeEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
@ -21,6 +21,7 @@ import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import com.ip.library.authors.model.AuthorEntity;
import com.ip.library.authors_books.model.AuthorsBooksEntity;
@Entity
@Table(name = "books")
@ -31,9 +32,9 @@ public class BookEntity extends BaseEntity {
@JoinColumn(name = "type_id", nullable = false)
@OrderBy("id ASC")
private TypeEntity type;
@ManyToMany(mappedBy = "books")
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id ASC")
private List<AuthorEntity> authors = new ArrayList<>();
private Set<AuthorsBooksEntity> authorsBooks = new HashSet<>();
public BookEntity() {
super();
@ -44,12 +45,6 @@ public class BookEntity extends BaseEntity {
this.type = type;
}
public BookEntity(String name, TypeEntity type, List<AuthorEntity> authors) {
this.name = name;
this.type = type;
this.authors = authors;
}
public String getName() {
return name;
}
@ -66,17 +61,25 @@ public class BookEntity extends BaseEntity {
this.type = type;
}
public List<AuthorEntity> getAuthors() {
return authors;
public Set<AuthorsBooksEntity> getAuthorsBooks() {
return authorsBooks;
}
public void setAuthors(List<AuthorEntity> authors) {
this.authors = authors;
public void setAuthors(Set<AuthorsBooksEntity> authorsBooks) {
this.authorsBooks = authorsBooks;
}
public boolean addAuthor(AuthorEntity author) {
AuthorsBooksEntity entity = new AuthorsBooksEntity(author, this);
boolean result = authorsBooks.add(entity);
if (!author.getAuthorsBooks().contains(entity))
author.getAuthorsBooks().add(entity);
return result;
}
@Override
public int hashCode() {
return Objects.hash(id, name, type, authors);
return Objects.hash(id, name, type);
}
@Override
@ -89,7 +92,6 @@ public class BookEntity extends BaseEntity {
return
Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getType(), type)
&& Objects.equals(other.getAuthors(), authors);
&& Objects.equals(other.getType(), type);
}
}

View File

@ -8,6 +8,7 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.ip.library.authors.model.AuthorEntity;
import com.ip.library.books.model.BookEntity;
public interface BookRepository extends
@ -24,4 +25,11 @@ public interface BookRepository extends
"from FavoriteEntity f " +
"where f.book.id = ?1")
int getBookSubscribersNumber(long bookId);
@Query(
"select ab.author " +
"from AuthorsBooksEntity ab " +
"where ab.book.id = ?1 " +
"order by ab.author.id"
)
List<AuthorEntity> getBookAuthors(Long bookId);
}

View File

@ -7,6 +7,7 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ip.library.authors.model.AuthorEntity;
import com.ip.library.books.model.BookEntity;
import com.ip.library.books.repository.BookRepository;
import com.ip.library.core.error.NotFoundException;
@ -75,7 +76,6 @@ public class BookService {
checkNameUniqueness(entity.getName());
existsEntity.setName(entity.getName());
existsEntity.setType(entity.getType());
existsEntity.setAuthors(entity.getAuthors());
return repository.save(existsEntity);
}
@ -90,4 +90,9 @@ public class BookService {
public int getBookSubscribersNumber(long bookId) {
return repository.getBookSubscribersNumber(bookId);
}
@Transactional(readOnly = true)
public List<AuthorEntity> getBookAuthors(long bookId) {
return repository.getBookAuthors(bookId);
}
}

View File

@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.ip.library.books.api.BookDto;
import com.ip.library.books.model.BookEntity;
import com.ip.library.books.service.BookService;
import com.ip.library.core.api.PageDto;
import com.ip.library.core.api.PageDtoMapper;
import com.ip.library.core.configuration.Constants;
@ -28,18 +29,24 @@ import jakarta.validation.Valid;
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
private final BookService bookService;
public UserController(UserService userService, ModelMapper modelMapper) {
public UserController(UserService userService, ModelMapper modelMapper, BookService bookService) {
this.userService = userService;
this.modelMapper = modelMapper;
this.bookService = bookService;
}
private BookDto toBookDto (BookEntity entity) {
BookDto bookDto = modelMapper.map(entity, BookDto.class);
bookDto.setAuthorId(bookService.getBookAuthors(
entity.getId()).stream().map(x -> x.getId()).toList());
return bookDto;
}
private UserDto toUserDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private BookDto toBookDto (BookEntity entity) {
return modelMapper.map(entity, BookDto.class);
}
private UserEntity toUserEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);

View File

@ -7,7 +7,6 @@ import java.util.Set;
import com.ip.library.books.model.BookEntity;
import com.ip.library.core.model.BaseEntity;
import com.ip.library.favorites.model.FavoriteEntity;
import com.ip.library.favorites.model.UserBookId;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;

View File

@ -51,7 +51,7 @@ class BooksTests {
list1.add(author2);
bookService.create(new BookEntity("book1", type));
bookService.create(new BookEntity("book2", type2));
book = bookService.create(new BookEntity("book3", type, list1));
book = bookService.create(new BookEntity("book3", type));
}
@Test
@ -59,8 +59,6 @@ class BooksTests {
Assertions.assertEquals(3, bookService.getAll().size());
Assertions.assertEquals("book3", book.getName());
Assertions.assertEquals(type, book.getType());
Assertions.assertTrue(book.getAuthors().contains(author1));
Assertions.assertTrue(book.getAuthors().contains(author2));
Assertions.assertEquals(0, bookService.getBookSubscribersNumber(book.getId()));
}
@ -86,7 +84,7 @@ class BooksTests {
bookService.delete(book.getId());
Assertions.assertEquals(2, bookService.getAll().size());
final BookEntity newEntity = bookService.create(
new BookEntity(book.getName(), book.getType(), book.getAuthors()));
new BookEntity(book.getName(), book.getType()));
Assertions.assertEquals(3, bookService.getAll().size());
Assertions.assertNotEquals(book.getId(), newEntity.getId());
}
@ -95,11 +93,11 @@ class BooksTests {
void nullNameTest() {
Assertions.assertThrows(
DataIntegrityViolationException.class,
() -> bookService.create(new BookEntity(null, book.getType(), book.getAuthors()))
() -> bookService.create(new BookEntity(null, book.getType()))
);
Assertions.assertThrows(
DataIntegrityViolationException.class,
() -> bookService.update(book.getId(), new BookEntity(null, book.getType(), book.getAuthors()))
() -> bookService.update(book.getId(), new BookEntity(null, book.getType()))
);
}
@ -107,11 +105,11 @@ class BooksTests {
void nullTypeTest() {
Assertions.assertThrows(
DataIntegrityViolationException.class,
() -> bookService.create(new BookEntity(book.getName() + "TEST", null, book.getAuthors()))
() -> bookService.create(new BookEntity(book.getName() + "TEST", null))
);
Assertions.assertThrows(
DataIntegrityViolationException.class,
() -> bookService.update(book.getId(), new BookEntity(book.getName() + "TEST", null, book.getAuthors()))
() -> bookService.update(book.getId(), new BookEntity(book.getName() + "TEST", null))
);
}
@ -119,11 +117,11 @@ class BooksTests {
void uniqueNameTest() {
Assertions.assertThrows(
IllegalArgumentException.class,
() -> bookService.create(new BookEntity(book.getName(), book.getType(), book.getAuthors()))
() -> bookService.create(new BookEntity(book.getName(), book.getType()))
);
Assertions.assertThrows(
IllegalArgumentException.class,
() -> bookService.update(book.getId(), new BookEntity(book.getName(), book.getType(), book.getAuthors()))
() -> bookService.update(book.getId(), new BookEntity(book.getName(), book.getType()))
);
}
}