【发布时间】:2019-07-26 07:33:02
【问题描述】:
我需要在 JPA 中写一个类似这样的查询:
SELECT
a.id,
b.status
FROM
atable a
JOIN btable b ON a.btable_id = b.id
where
(
(
b.status = 'INITIAL'
and a.main_atable_id is null
)
or exists (
SELECT
1
FROM
atable a2
JOIN btable b2 ON a2.btable_id = b2.id
WHERE
b2.status = 'INITIAL'
and b2.main_atable_id = a.id
)
);
如您所见,atable 有一个名为 main_atable_id 的列,它创建了父子关系,其想法是存在一个主版本,其子版本是重复的。
我需要构建一个与父查询几乎相同的子查询。我会手动编写它只是复制代码,但如果可能的话,我想通过重用主查询的Specification 来保持简单。
我的主要查询现在看起来像这样:
public Page<AtableDTO> findAtables(AtableSearchDTO filter, Pageable pageable) {
Specifications<Atable> where = Specifications.where(alwaysTrue());
if(filter.getStatus() != null) {
where = where.and(statusEquals(filter.getStatus()));
}
Page<AtableDTO> resultPage = atableRepository.findAll(where, new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "id")).map(atableMapper::toDto);
}
public Specification<Atable> alwaysTrue() {
return (root, query, cb) -> cb.and();
}
public Specification<Atable> statusEquals(AtableStatus value) {
return (root, query, cb) -> cb.equal(root.get("status"), value);
}
我只需要知道:
1) 是否可以重复使用相同的Specification
2)如果是,你能证明这个或任何其他简单的例子
谢谢
【问题讨论】:
-
请向我们展示您的尝试。
标签: java jpa subquery criteria-api