代码之家  ›  专栏  ›  技术社区  ›  Alex

springdatajpa使用SpEL语法有条件地构建查询

  •  0
  • Alex  · 技术社区  · 6 年前

    我试图根据boolean@Param构建一个查询,困难在于我构建查询的结尾时没有使用经典运算符(=,<>…)。

    例如,假设我要获取与Account对象无关的所有Sales对象(如果在@Param中传递false)或与Account相关的所有Sales对象(如果在@Param中传递true):

    @Query("SELECT sale .... 
     WHERE sale.account :#{isbound ? NOT NULL : IS NULL}")
    public List<Sale> getSales(@Param("isbound") boolean isBound);
    

    我尝试了一些基于Spring官方文档的语法( https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions ),但它们的所有示例都是在表达式之前使用运算符,例如:entity=#{the#u expression}。

    1 回复  |  直到 6 年前
        1
  •  2
  •   RJ.Hwang    6 年前

    重构查询代码,如下所示:

    @Query("SELECT sale .... 
            WHERE (true = :isbound and sale.account is not null)
              or (false = :isbound and sale.account is null)")
    public List<Sale> getSales(@Param("isbound") boolean isBound);