JPQL 通过将 ID 传递给 IN 子句来排序实体

JPQL order entities by passed IDs to IN clause

是否可以通过我作为参数传递给具有 spring 数据存储库的 IN 子句的 ID 对实体进行排序?

例如:

SELECT e FROM Employee WHERE e.id IN (:employeeIds);

和 employeeIds = {1,2,3,4,5}

我的列表和来自 JPARepository 的结果将是相同顺序的实体:

Employee={id:1, ...}, Employee={id:2, ...}, Employee={id:3, ...}

根据您使用的数据库,您可以从传递的数组创建一个 table 并将实体连接到 is,类似于:

select e
from (values (1), (2), (3), ...) as t(id)
inner join employee e on t.id = e.id;

这可以被评估为原生查询:

entityManager.createNativeQuery(
    "select e " +
    "from (values (1), (2), (3), ...) as t(id) " +
    "inner join employee e on t.id = e.id", Employee.class)
    .gerResultList();

但是如您所见,您必须自己编写查询或传递大量 od 参数(可能在循环中)。