我有这个任务存储库:
@Repository
interface MissionRepository: CrudRepository<MissionEntity, String>, JpaSpecificationExecutor<MissionEntity>
在我的任务服务类中,我想获取所有具有给定参数 Set
的 countryId
部分的任务:
fun findAllByCountryIdIn(countryIds: Set<String>): List<MissionEntity> =
missionRepository.findAll(where(countryIdIn(countryIds)))
}
countryIdIn
(使用 in
谓词)来自哪里:
class MissionSpecifications {
companion object {
fun countryIdIn(countryIds: Set<String>): Specification<MissionEntity> =
Specification { root, _, _ -> root.get<String>("countryId").`in`(countryIds) }
}
}
但是当Set
为空时,我得到了一个可预测的sql错误。有没有办法仅当给定的集合不为空时才激活 where 子句?没有 if/else 检查?也许我的规范语法可以改进以避免这个 sql 错误?
最佳答案
我宁愿早点回来。因此,如果您一开始不需要,就不要添加 where 。您可以通过多种方式做到这一点,例如使用takeIf
、简单的 if
、when
等
仅列出一些示例:
-
fun findAllByCountryIdIn(countryIds: Set<String>) = countryIds.takeIf { it.isNotEmpty() } ?.let { missionRepository.findAll(where(countryIdIn(it))) } ?: // what should be returned otherwise? emptyList? all? exception?
-
fun findAllByCountryIdIn(countryIds: Set<String>) = countryIds.ifEmpty { // what should be returned? emptyList? all entries? }.let { missionRepository.findAll(where(countryIdIn(it))) } }
如果
fun findAllByCountryIdIn(countryIds: Set<String>) = if (countryIds.isEmpty()) /* what should be returned? */ else missionRepository.findAll(where(countryIdIn(countryIds))) }
如果您只是解决countryIdIn
,例如通过传递一个空元素,您将查询本身的控制权交给了辅助方法。如果你真的想要那样,那好吧......但否则我不会那样做。
为什么我不这样做?如果我稍后返回该特定代码并阅读 findAll(where(countryIdIn(countryIds)))
。如果集合为空,我需要多长时间才能确定返回所有条目?事实是:我不能不查看 countryIdIn
本身。但这是我的看法。
关于jpa - 空列表时的表达式 `in`(spring data jpa规范),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52291683/