1

I want to make a simple book organizing app with Java Spring.

I have attached an image at the bottom of the page. Add the number of works as in the webpage.

It has an author entity and a book title entity. The author entity has a one-to-many relationship with the title entity of the book.

//Author entity

1 auther_id <-primary key

2 auther_name

3 birthplace

//Book title entity

1 title_id <-primary key

2 title_name

3 auther_id <-foreign key

Display it as a table in html. Then, create a number of works column for each author. For example, there are 3 Shakespeare books. Therefore, I would like to display "3" in the number of works column. How can I do it?

AutherRepository.java

 @Repository
 public interface AutherRepository extends JpaRepository <AutherEntity, Long> {
 }

BookTitleRepository.java

 @Repository
 public interface AutherRepository extends JpaRepository <BookTitleEntity, Long> {
    public long countByAuther_id(long auther_id);
 }

BookService.java

@Service
@Transactional
public class BookService {
   @Autowired
   private AutherRepository autherRepository;
   private BookTitleRepository booktitleRepository;

   Long countByAuther_id(long auther_id);
}

enter image description here

Aledun
  • 13
  • 4
  • Possible duplicate of https://stackoverflow.com/questions/10696490/does-spring-data-jpa-have-any-way-to-count-entites-using-method-name-resolving – Victor Gubin Aug 25 '21 at 15:40
  • I checked the URL, but it did not solve the problem. I wrote the code halfway through, but I don't know how to continue. – Aledun Aug 26 '21 at 10:56

1 Answers1

1

What you can do is:

In the author entity:

//the mappedBy is the name of the variable at Book entity
@OneToMany(mappedBy = "author", cascade = { CascadeType.ALL })
private List<Book> books;

In the book entity:

@ManyToOne
@JoinColumn(name = "author_id")
private Author author;

Then you can always call the size of the books prop of author like this:

Author author1 = authorRepository.findById(author_id);
author1.books().size // <----- here it is what you want