JavaSpringBootJPA表层次结构
我在数据库中只有一个名为Student的表。以下是我的代码中针对它的jpa实体:
@Entity
@Table(name = "student")
public class Student{
@Id
private Long id;
@Column
private String firstName;
@Column
@Embedded
@JsonUnwrapped
private School school;
}
public class School{
private Integer grade;//eg. 2nd, 3rd
private String type; //eg. primary, secondary
}
到目前为止,代码只用于获取所有学生及其数据或获取特定学生。因此,DB模式就是这样。但是现在,我们有了一个新的功能,我们需要根据特定的年级进行搜索,并获取该特定年级的所有学生。或者为特定学校类型招收所有学生,例如小学的所有学生。因此,需求完全相反,因此我们需要将以下模式的返回发送到前端:
class SchoolResponseDTO{
private String schoolType;
private List<Integer> grades;
}
class Grade{
private Integer id;
private List<Integer> studentId;
}
更详细地说,从现在开始,我们需要找到所有的学校类型,然后,该学校类型中的所有年级,然后,该学校类型和年级中的所有学生
到目前为止,我们一直在使用Spring JpaRepository来满足我们的需求。我觉得这个新需求需要定制查询,我不认为使用JPARepository可以直接处理这个问题。我只是想知道你是怎么想的。在没有自定义sql查询的情况下可以做到这一点吗
# 1 楼答案
您可以使用Spring数据并使用类似以下查询属性表达式的内容。从文档:
检查链接 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions
希望能有帮助