Link authors and books

master
Dmitry Isaenko 2024-01-17 19:40:03 +03:00
parent 95e26e287a
commit 261d5b3ae4
4 changed files with 9 additions and 11 deletions

View File

@ -5,16 +5,10 @@ import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ru.redrise.marinesco.library.Author;
import ru.redrise.marinesco.library.Book;
@Repository
public interface BookRepository extends JpaRepository<Book, Integer>{
List<Book> findBySeriesContainingIgnoreCase(String title);
List<Book> findByTitleContainingIgnoreCase(String title);
List<Book> findAllByAuthorsContains(Author author);
}

View File

@ -1,7 +1,10 @@
package ru.redrise.marinesco.library;
import java.util.List;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
@ -14,6 +17,9 @@ public class Author {
private Long id;
private String authorName;
@ManyToMany(mappedBy = "authors")
private List<Book> books;
public Author(String name){
this.authorName = name;
this.id = (long) name.hashCode();

View File

@ -8,6 +8,7 @@ import java.util.Set;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Transient;
import lombok.AccessLevel;

View File

@ -9,7 +9,6 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.redrise.marinesco.data.AuthorRepository;
import ru.redrise.marinesco.data.BookRepository;
import ru.redrise.marinesco.library.Author;
import ru.redrise.marinesco.library.Book;
@ -17,11 +16,9 @@ import ru.redrise.marinesco.library.Book;
@RequestMapping("/author")
public class AuthorController {
private AuthorRepository authorRepository;
private BookRepository bookRepository;
public AuthorController(AuthorRepository authorRepository, BookRepository bookRepository){
public AuthorController(AuthorRepository authorRepository){
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
}
@GetMapping("/{authorId}")
@ -33,7 +30,7 @@ public class AuthorController {
return "author";
}
List<Book> books = bookRepository.findAllByAuthorsContains(author);
List<Book> books = author.getBooks();
model.addAttribute("author", author);
model.addAttribute("books", books);