我正在使用Spring Boot v1.5.3在我的代码中,我有很多条件的搜索操作。
public Page<ParentObject> search(Pageable pageable) {
Specification<ParentObject> specification = (root, cq, cb) -> {
Predicate p = cb.and(
cb.equals(root.get("child").get("id"), "someValue"),
// a lot of predicates appended by conditions
);
return p;
};
Sort newSort = pageable.getSort().and(new Sort(Sort.Direction.ASC, "child.id"));
pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), newSort)
Page<ParentObject> result = parentObjectRepository.findAll(specification, pageable);
return result;
}
问题是我的parent
表包含带有索引的child_id
字段。我希望SQL像:
SELECT .... FROM parent p INNER JOIN child c ON c.id = p.child_id WHERE ...
ORDER BY p.child_id ASC;
但是结果我有:
SELECT .... FROM parent p INNER JOIN child c ON c.id = p.child_id WHERE ...
ORDER BY c.id ASC;
请注意ORDER BY
子句。如果我有c.id
索引,则该索引不参与并且搜索速度很慢。如果我有ORDER BY p.child_id
,它的工作速度会更快。我尝试使用
Sort newSort = pageable.getSort().and(new Sort(Sort.Direction.ASC, "child"));
但是它不能按预期工作。实体:
public class ParentObject {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "child_id", referencedColumnName = "id")
private ChildObject child;
}
我无法用本机SQL替换它,因为此搜索规范包含30多个if / else语句,并且将需要大量时间来重写代码。
我该如何解决这个问题?预先感谢您的回答。
最后,我找到了解决方案。众所周知,ORM通过实体与数据库一起工作。我所有的实体都有String(UUID)值作为ID。因此,我将以下代码添加到了ParentObject中: