spring data jpa 与 postgres 的问题 - 尝试将超出范围的整数作为 2 字节值发送

Jul*_*lie 3 postgresql spring-data-jpa

quoteEntitiesPage = quoteRepository.findAllByQuoteIds(quoteIds, pageRequest);

如果 quoteIds 参数的计数高于 Short.MAX_VALUE,上面的查询会给出错误“尝试将超出范围的整数作为 2 字节值发送”。

在此处获取所有报价实体的最佳方法是什么?我的 Quote 类有 id(long) 和 quoteId(UUID) 字段。

Anx*_*nxo 6

当使用“ select ... where x in (list) ”类型的查询(例如您的查询)时,Spring 会为每个列表元素添加一个绑定参数。PostgreSQL 将查询中的绑定参数数量限制为 Short.MAX_VALUE 绑定,因此当列表长于此时,您会收到该异常。

此问题的一种简单解决方案是将列表划分为块,查询每个块,然后合并结果。

像这样,使用番石榴:

List<QuoteEntity> result = new ArrayList<>();
List<List<Long>> partitionedQuoteIds = Lists.partition(quoteIds, 10000);
for (List<Long> partitionQuoteIds: partitionedQuoteIds) {
  result.addAll(quoteRepository.findAllByQuoteIds(partitionQuoteIds))
}
Run Code Online (Sandbox Code Playgroud)

这在分页时非常浪费,但对于您的用例来说可能就足够了。