JpaRepository查询含非空集合判断时抛出UnsupportedOperationException问题
解决JPA查询中集合null判断结合
size()引发的UnsupportedOperationException问题 问题场景
以下JpaRepository方法执行时会抛出UnsupportedOperationException:
@Query("select h from HistoricoInteracaoEntidade h " + "where h.cliente.id = :clienteId " + "and h.author in :authors " + "and h.isBlockedDueConvert = false " + "and h.descricao is not null " + "or (h.justificativas is not null and size(h.justificativas) > 0) " + "and h.moment > :conversionDateMinusDays " + "order by h.moment asc") List<HistoricoInteracaoEntidade> getElegibleInteractions( @Param("clienteId") String clienteId, @Param("authors") List<InteracaoAuthor> authors, @Param("conversionDateMinusDays") LocalDateTime conversionDateMinusDays);
移除h.justificativas is not null and 条件后异常消失,但业务上justificativas可能被保存为null数组,必须保留该判断;将or条件替换为and h.justificativas is not null仍无法解决问题。
问题原因
- 逻辑优先级错误:JPQL中
and优先级高于or,原查询的or分支未与h.descricao is not null分组,导致整个where子句逻辑被解析为不符合预期的组合,引发JPA解析异常。 size()方法的兼容性问题:部分JPA实现对size(集合) > 0结合null判断的解析存在缺陷,即使加了is not null,仍可能因执行顺序问题触发不支持的操作。
解决方案
修正查询的逻辑优先级,同时使用JPQL标准的is not empty替代size() > 0处理集合非空判断,完整代码如下:
@Query("select h from HistoricoInteracaoEntidade h " + "where h.cliente.id = :clienteId " + "and h.author in :authors " + "and h.isBlockedDueConvert = false " + "and h.moment > :conversionDateMinusDays " + "and (h.descricao is not null " + " or (h.justificativas is not null and h.justificativas is not empty)) " + "order by h.moment asc") List<HistoricoInteracaoEntidade> getElegibleInteractions( @Param("clienteId") String clienteId, @Param("authors") List<InteracaoAuthor> authors, @Param("conversionDateMinusDays") LocalDateTime conversionDateMinusDays);
说明
- 用括号将
h.descricao is not null和(h.justificativas is not null and h.justificativas is not empty)包裹,确保这两个条件作为整体与其他and条件结合,修正逻辑优先级。 is not empty是JPQL专门用于判断集合非空的语法,相比size() > 0更可靠,能与is not null配合安全处理null数组的场景。
内容的提问来源于stack exchange,提问作者Davi Américo
相关产品推荐
相关产品推荐

