Aledun
Aledun

Reputation: 13

Spring JPA - How to count number of Foreign key

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

Upvotes: 1

Views: 976

Answers (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

Upvotes: 1

Related Questions