spring data JPA查询连接空字段



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

@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为null时,response中都不包含production .

基本上我想要的是连接品牌名称,标题和标题,如果品牌不是null,如果它是空的连接标题和标题。

我已经尝试了很多使用CASE的方法…

在WHERE子句中连接字符串时,使用路径操作符";从ProductOption导航到product,再从那里导航到brand

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

在生成的SQL语句中创建2个INNER join,排除没有product或没有brandproductProductOption

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

@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);

最新更新