java - JPA findAll 按链表大小排序

标签 java spring spring-data-jpa jpql

我遇到了一个问题,我不知道是否可以使用 JPA 来解决。

我正在尝试使用 JPA 进行查询并进行以下操作:

获取所有具有类(class)实体字段(id、名称)的类(class)以及一个非持久字段(@Transient),该字段将填充与该类(class)相关的所有学生人数

像这样:

List<Course> courses = courseRepository.findAll();

而是获取(出于示例目的表示为 json)

[{1, soccer}, {2, art}, {3, singing}]

我需要这样的东西

[{1, soccer, 2}, {2, art, 0}, {3, singing, 1}]

如您所见,值 2、0 和 1 是所有相关行的学生表的计数

Student table
| id | name | description | course |
|  1 | thg1 | a thing     | 1      |
|  2 | thg2 | another one | 1      |
|  3 | thg3 | one more    | 3      |   

Course Table
| id | name | 
|  1 | soccer |     
|  2 | art |     
|  3 | singing |     

因此,限制是一个学生只能参加一门类(class)。

使用 JPA 我想选择所有类(class),但是由于我使用的是分页,所以我无法在 spring 部分完成它(我的意思是作为一项服务),我正在尝试直接使用 JPA 来完成,是吗我有什么办法可以做到这一点?也许有规范?想法?

谢谢

最佳答案

您可以使用 Hibernate 中的 @Formula 注释:

@Formula("select count(*) FROM student s WHERE s.course = id")
private int totalStudents;

Sometimes, you want the Database to do some computation for you rather than in the JVM, you might also create some kind of virtual column. You can use a SQL fragment (aka formula) instead of mapping a property into a column. This kind of property is read only (its value is calculated by your formula fragment).

@Formula("obj_length * obj_height * obj_width")
public long getObjectVolume()

The SQL fragment can be as complex as you want and even include subselects.

hibernate reference

或者,您可以使用双向关系来计算学生数:

@OneToMany(mappedBy="course")
private List<Student> students;

public int getTotalStudents() {
    return students.size();
}

或者使用 transient 字段:

@OneToMany(mappedBy="course")
private List<Student> students;

@Transient
private int studentCount;

@PostLoad
public void setStudentCount() {
    studentCount = students.size();
}

为避免 Cepr0 提到的 N+1 问题,您可以将获取模式设置为加入:

@OneToMany(mappedBy="course")
@Fetch(FetchMode.JOIN)
private List<Student> students;

关于java - JPA findAll 按链表大小排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50750028/

相关文章:

java - 带有 MariaDB 驱动程序的 MySQL 服务器产生日期排序错误

java - SSL 握手异常 : Received fatal alert: handshake_failure followup

java - 对 AWS Spring Boot 配置文件进行单元测试 - 可能吗?

java - 管理 Oracle BFILES

java - Spring Data JPA 如何为多个实体构建通用存储库?

java - Spring data jpa嵌套事务回滚不删除插入?

java - 如何解压缩使用 CipherInputStream 和 ZipInputStream 压缩和加密的文件

java - 黑莓替换字符串的方法?

java - 删除集成测试时创建 bean 的异常,该异常不会出现在标准应用程序启动中

java - Spring:@PropertySource 的编程等价物是什么