Spring JPA - 如何计算外键的数量
Spring JPA - How to count number of Foreign key
我想用 Java Spring.
制作一个简单的书籍整理应用程序
我在页面底部附上了一张图片。
添加网页中的作品数量
它有一个作者实体和一个书名实体。
作者实体与书名实体是一对多关系。
//作者实体
1 auther_id <-主键
2 auther_name
3 出生地
//书名实体
1 title_id <-主键
2 title_name
3 auther_id <-外键
将其显示为 html 中的 table。然后,为每个作者创建一些作品列。
例如,莎士比亚有 3 本书。因此,我想在作品数量栏中显示“3”。
我该怎么做?
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
您可以做的是:
在作者实体中:
//the mappedBy is the name of the variable at Book entity
@OneToMany(mappedBy = "author", cascade = { CascadeType.ALL })
private List<Book> books;
书中实体:
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
那么你可以随时这样调用作者的书籍道具的大小:
Author author1 = authorRepository.findById(author_id);
author1.books().size // <----- here it is what you want
我想用 Java Spring.
制作一个简单的书籍整理应用程序我在页面底部附上了一张图片。 添加网页中的作品数量
它有一个作者实体和一个书名实体。 作者实体与书名实体是一对多关系。
//作者实体
1 auther_id <-主键
2 auther_name
3 出生地
//书名实体
1 title_id <-主键
2 title_name
3 auther_id <-外键
将其显示为 html 中的 table。然后,为每个作者创建一些作品列。 例如,莎士比亚有 3 本书。因此,我想在作品数量栏中显示“3”。 我该怎么做?
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
您可以做的是:
在作者实体中:
//the mappedBy is the name of the variable at Book entity
@OneToMany(mappedBy = "author", cascade = { CascadeType.ALL })
private List<Book> books;
书中实体:
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
那么你可以随时这样调用作者的书籍道具的大小:
Author author1 = authorRepository.findById(author_id);
author1.books().size // <----- here it is what you want