【问题标题】:JPA query to concat null fieldJPA查询连接空字段
【发布时间】:2021-05-13 14:30:49
【问题描述】:

您好,这是连接品牌名称、标题和下标题的查询

@Query(value="SELECT c FROM ProductOption c WHERE  cast( c.id AS string ) like %:search% or CONCAT(COALESCE(c.product.brand.name,''),' ',c.product.title,' ',c.underTitle) like %:search%")
Page<ProductOption> findAllBySearch(String search,Pageable pageable);

但是每次brand为空时,productoption都不包含在响应中..

基本上我想要的是连接品牌名称、标题和下标题,如果品牌不为空,如果它为空,则按标题和下标题连接..

我已经尝试了更多使用 CASE etd 的方法...

【问题讨论】:

    标签: jpa spring-data-jpa jpql


    【解决方案1】:

    当您连接 WHERE 子句中的字符串时,您使用 path operator "." 从您的 ProductOption 导航到 product 并从那里导航到 brand。

    @Query(value="... CONCAT(COALESCE(c.product.brand.name,''),' ',c.product.title,' ',c.underTitle) like %:search%")
    

    这会在生成的 SQL 语句中创建 2 个INNER JOINs,排除没有product 或没有brand 的product 的ProductOptions。

    您可以通过 FROM 子句中的defining LEFT JOINs 并在 WHERE 子句中引用这些 JOINS 的别名来避免这种情况:

    @Query(value="SELECT c FROM ProductOption c LEFT JOIN c.product p LEFT JOIN p.brand b WHERE  cast( c.id AS string ) like %:search% or CONCAT(COALESCE(b.name,''),' ',p.title,' ',c.underTitle) like %:search%")
    Page<ProductOption> findAllBySearch(String search,Pageable pageable);
    

    【讨论】:

      猜你喜欢
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2012-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多