【问题标题】:using in clause inside jpa query gives Operand should contain 1 column(s) error在 jpa 查询中使用 in 子句给出 Operand should contain 1 column(s) 错误
【发布时间】:2017-09-25 10:18:38
【问题描述】:

我正在尝试在 jpa 查询中使用 in 子句,但它给出了 Operand should contain 1 column(s) 错误。

这是我的查询:

@Query(value = "select e from Table e where " +
            "((:plantId is null and :unitId is null and :functionalLocationId is null) or" +
            " (:functionalLocationId is not null and e.functionalLocation.id in (select f.id from FunctionalLocation f where f.id = :functionalLocationId)) or" +
            " (:unitId is not null and :functionalLocationId is null and e.functionalLocation.unit.id in (select u.id from Unit u where u.id = :unitId)) or" +
            " (:plantId is not null and :unitId is null and :functionalLocationId is null and e.functionalLocation.unit.plant.id in (select p.id from Plant p where p.id = :plantId))) and" +
            "((:equipmentTagNumbers) is null or e.tagNo in (:equipmentTagNumbers)) and" +
            "(:startDate is null or e.lastUpdateDate >= :startDate) and" +
            "(:endDate is null or e.lastUpdateDate <= :endDate)" +
            "order by e.id desc")

:equipmentTagNumbers 属性是 Lis&lt;String&gt;,如果我为它发送 null,则查询按预期工作,但是当我发送实际数据时,它会给出错误。

有什么建议吗?

【问题讨论】:

  • 您的查询有一些子查询返回超过 1 列,而您只希望 1 列,例如,“where x = (select x,y from abr)”
  • 尝试添加您在其中形成查询并设置参数的 jpa 查询调用
  • @MaciejKowalski 我试过但结果是一样的
  • @kyur 您是否使用 eclipselink 作为您的 JPA 实现?刚刚遇到同样的问题,根据我的队友的说法,这是我们的 eclipselink 版本中的一个错误(另见forum.spring.io/forum/spring-projects/data/…

标签: java mysql jpa


【解决方案1】:

据我了解,如果您的参数是 array,则 jpa 查询中没有 isEmptylength,就像在这种情况下一样。 @SOlsson 是对的,(1,2,4 is null or... 是无效的 Sql,所以我决定在我的查询中添加一个额外的参数,以检查它是否是 null,所以我的最后一个查询如下:

        ...
            "((:hasEquipmentNumbers) is null or e.tagNo in (:equipmentTagNumbers)) and" 
        ...

:hasEquipmentNumbers 是一个布尔值,我可以分配 null,所以如果它为 null,那么没有人会受到伤害,如果不是,我可以毫无问题地运行我的 IN 子句。

PS:我标记了他的答案,因为它看起来像一个答案。但我按照我解释的方式实现了。

【讨论】:

    【解决方案2】:
    ((:equipmentTagNumbers) is null or...
    

    变成

    (1,2,4 is null or...
    

    这不是正确的 SQL。

    改为这样:

    @Query(value = "select e from Table e where " +
            "..." +
            (equipmentTagNumbers == null ? "" : "e.tagNo in (:equipmentTagNumbers)) and ") +
            "..." +
            "order by e.id desc")
    

    这样equipmentTagNumbers为null时不会影响查询。

    【讨论】:

    • 我认为这不会起作用,因为equipmentTagNumbers 属性已在运行时填充。所以我无法检查它是否为空。
    • 为什么这是公认的答案对我来说毫无意义。 equipmentTagNumbers 在编译时在 @Query 注释中不可用。
    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多