我有一个任务存储库:
@Repository
interface MissionRepository: CrudRepository<MissionEntity, String>, JpaSpecificationExecutor<MissionEntity>在我的任务服务类中,我想获取所有具有给定参数Set的Set部分的任务。
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子句?如果没有检查的话?也许我的规范语法可以改进以避免这个sql错误?
发布于 2018-09-12 09:46:36
我宁愿早点回来。所以,如果一开始不需要它,就不要添加一个where。您可以通过多种方式这样做,例如使用takeIf、简单的if、when等。
只列出一些示例:
takeIf
missionRepository.findAll(where(countryIdIn(it))) findAllByCountryIdIn(countryIds: Set) = countryIds.takeIf { it.isNotEmpty() } ?.let {it.isNotEmpty} ?://否则应该返回什么?emptyList?全?例外?if
missionRepository.findAll(where(countryIdIn(countryIds))) findAllByCountryIdIn(countryIds: Set) = if (countryIds.isEmpty()) /*,应该返回什么?*/ else countryIds}如果您只是解决countryIdIn,例如,通过传递一个空元素,则将查询本身的控制权交给助手方法。如果你真的想要的话,好吧.但否则我不会那么做的。
我为什么不这么做?如果我稍后返回到特定的代码并读取findAll(where(countryIdIn(countryIds)))。如果集合是空的,我需要多长时间才能确定返回所有条目?事实是:我不能不看countryIdIn本身。但这是我的观点。
发布于 2018-09-12 09:41:58
只要在创建Specification的函数中进行测试,如果集合是空的,那么只返回一个空的Specification。
发布于 2018-09-12 13:24:24
另一种解决办法是:
@Repository
interface MissionRepository: JpaRepository<MissionEntity, String> {
fun findByCountryIdIn(countryIds: Set<String>, pageable: Pageable): Page<MissionEntity>
}您可以在其中添加分页。
https://stackoverflow.com/questions/52291683
复制相似问题