我在Spring数据接口中定义了以下JPA查询
@Query("select tr.bidder.supplierId " +
"from TaskResponse tr " +
"where tr.task.id = :taskId " +
"and tr.extended = true " +
"and tr.bidder.supplierId not in (:extendedSupplierIds)")
Set<String> supplierIdsDueTaskRevocationNotification(UUID taskId,
Set<String> extendedSupplierIds);
当对Postgres数据库执行查询时,查询工作良好,但如果对H2数据库执行时出现以下错误,则会失败:
Syntax error in SQL statement
SELECT BIDDER1_.SUPPLIER_ID AS COL_0_0_
FROM TASK_RESPONSES TASKRESPON0_
CROSS JOIN BIDDERS BIDDER1_
WHERE TASKRESPON0_.BIDDER_ID=BIDDER1_.ID
AND TASKRESPON0_.TASK_ID=?
AND TASKRESPON0_.EXTENDED=1
AND (BIDDER1_.SUPPLIER_ID NOT IN ()[*])";
expected "NOT, EXISTS, INTERSECTS, UNIQUE";
看起来问题就在于not in (:extendedSupplierIds)
谓词,因为如果删除该谓词,查询将在两个数据库上执行而不会出现错误。
有什么方法可以重写这个查询以便它在两个数据库上都能工作吗?
更新
根据一个应答者的建议,我将查询更改为使用显式联接。
@Query("select b.supplierId " +
"from TaskResponse tr " +
"join tr.bidder b " +
"join tr.task t " +
"where t.id = :taskId " +
"and tr.extended = true " +
"and b.supplierId not in (:extendedSupplierIds)")
Set<String> supplierIdsDueTaskRevocationNotification(UUID taskId,
Set<String> extendedSupplierIds);
但没什么区别,我还是会犯同样的错误。
发布于 2021-12-16 17:01:48
这是由bug引起的,可能是在org.hibernate.dialect.H2Dialect中。
如果将空集作为查询参数值传递,该参数值构成JPQL查询中"not in“谓词的右侧,则在对H2数据库运行时查询将失败。若要解决此问题,请使用包含单个空元素的集合。
例如,在调用此查询时,请使用
UUID taskId = UUID.randomUUID();
Set<String> supplierIds = // get this from somewhere
if (supplierIds.isEmpty()) {
supplierIds.add(null);
}
myRepository.supplierIdsDueTaskRevocationNotification(taskId, supplierIds)
https://stackoverflow.com/questions/70381590
复制相似问题