如何在实体之间创建JPA规范联接



我想创建基于JPA规范的过滤器。我使用的是春季数据。

我的实体:

public class Section {
/*some other fields*/
@OneToMany
@JoinTable(
name = "section_objective",
joinColumns = @JoinColumn(name = "section_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "objective_id", referencedColumnName = "id")
)
private List<Objective> objectives;
}
public class Objective {
/*some other fields*/
@OneToMany
@JoinTable(
name = "objective_question",
joinColumns = @JoinColumn(name = "objective_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "question_id", referencedColumnName = "id")
)
private List<Question> questions = new ArrayList<>();
}
public class Question {
/*some fields, below code is not important*/
}

实体依赖关系为:-一对多->目标-一对多->问题实体没有关于父关系的信息(例如,我无法从问题转到Java代码中分配问题的目标(。

我有一个问题过滤器类,它可以转换为规范。我想把所有的问题都记在第节里。

通常,我会使用下面写的SQL查询来获得第节中的所有问题。

SELECT q.*
FROM
question q
JOIN
objective_question oq ON oq.question_id = q.id
JOIN
objective o ON o.id = oq.objective_id
JOIN
section_objective so ON so.objective_id = o.id
JOIN
section s ON s.id = so.section_id
WHERE
s.id IN (1,2);

我尝试过用Join创建规范,但不知道当问题上的Objective引用不可用时如何创建Join。

Specification.<Question>where((root, query, criteriaBuilder) ->
root.join("section") /*throws error because **section** is not a part of attribute on Question */
.in(List.of(1L, 2L)));

您可以使用以下库:https://github.com/turkraft/spring-filter

它将允许您运行搜索查询,例如:

/search?filter= 平均值(评级(>4.5品牌名称("奥迪"、"路虎"(和(年份>2018km<50000(和颜色"白色">事故为空

即使您没有API,您也可以运行搜索查询,如果您愿意,库基本上将搜索输入编译为JPA谓词或规范。它将顺利处理所有联接查询,而不必担心众所周知的n+1查询问题。

您可以构建如下规范:

import static com.turkraft.springfilter.FilterBuilder.*;
Specification<Section> spec = new FilterSpecification<Section>(
and(
in("id", numbers(1, 2, 3)),
equal("objectives.questions.field", "some value")
)
);
// basically telling: get the sections which have id 1, 2 or 3, AND which have the field 'field' of the objectives questions' equal to 'some value'

您不需要配置任何内容,只需导入依赖项:

<dependency>
<groupId>com.turkraft</groupId>
<artifactId>spring-filter</artifactId>
<version>1.0.2</version>
</dependency>

最新更新