Spring data jpa SPEL动态添加where JPQL子句

问题描述 投票:0回答:1

查询参数对象

data class GetSourceListRequest(
    val category: List<Int>,
    val text: String,
    val tag: List<Int>,
    val order: Sort.Direction,  
    val pageSize: Int,    
    val currentPage: Int
)

查询存储库

interface ISourceItemDao : JpaRepository<SourceItemEntity, Long>, CrudRepository<SourceItemEntity, Long> {
  @Query(
        """
        select e.id 
        from SourceItemEntity e
        left join SourceItemToCategoryEntity ic on e.id = ic.itemId
        #{request.category.size() > 0 ? 'where ic.categoryId in (:#{#request.category}' : 'q')}
        where ic.categoryId in (:#{#request.category})
        """
    )
    fun getIdByCondition(request: GetSourceListRequest, pageable: Pageable): Page<Long>
}

关键代码是这一行(这里的代码是错误的):

#{request.category.size() > 0 ? 'where ic.categoryId in (:#{#request.category})' : ''}

希望

#{request.category}
为空列表时不加
where
子句,非空列表时加
where
子句

刚学

Spring Data JPA
,没搞明白这样的spel语句怎么写

jpa spring-data-jpa spring-el
1个回答
0
投票

首先,在您的代码中,您不需要从具有扩展

CrudRepository
接口的
JpaRepository
进行扩展。 我还看到您重复了
where
子句,所以我建议只保留其中一个使用
Collection.isEmpty()
方法简化的子句:

interface ISourceItemDao : JpaRepository<SourceItemEntity, Long> {
  @Query(
        """
        select e.id 
        from SourceItemEntity e
        left join SourceItemToCategoryEntity ic on e.id = ic.itemId
        #{request.category.isEmpty() ? '' : ' where ic.categoryId in (:#{#request.category}')}
        """
    )
    fun getIdByCondition(request: GetSourceListRequest, pageable: Pageable): Page<Long>
}

这里的基础表达式是

select e.id 
from SourceItemEntity e
left join SourceItemToCategoryEntity ic on e.id = ic.itemId

附加空字符串或

' where ic.categoryId in (:#{#request.category}'

取决于

request.category
是否为空

© www.soinside.com 2019 - 2024. All rights reserved.