jpa - 空列表时的表达式 `in`(spring data jpa规范)

标签 jpa kotlin spring-data-jpa jpql

我有这个任务存储库:

@Repository
interface MissionRepository: CrudRepository<MissionEntity, String>, JpaSpecificationExecutor<MissionEntity>

在我的任务服务类中,我想获取所有具有给定参数 SetcountryId 部分的任务:

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 、简单的 ifwhen

仅列出一些示例:

  • takeIf

    fun findAllByCountryIdIn(countryIds: Set<String>) = countryIds.takeIf { it.isNotEmpty() }
                 ?.let { missionRepository.findAll(where(countryIdIn(it))) } 
                 ?: // what should be returned otherwise? emptyList? all? exception?
    
  • ifEmpty (Kotlin >=1.3)

    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/

相关文章:

java - Hibernate 查询语法异常

java - 将属性绑定(bind)到从 JavaFx/TornadoFX 控件派生的值的正确方法

对连接表的 JPA 查询

java - 跨多个 Web 服务的交易

Kotlin 合约推断返回值而不是参数值

java - 如何从 Kotlin/Java 中运行 Kotlin-Script (.kts) 文件?

java - 使用 spring-data-jpa 自定义 ItemReader

java - 如何使用 Spring Data JPA 访问 Azure AD 集成的 Postgres DB?

Spring JPA 定义了多个 EntityManagerFactory 但存储库仍然只访问一个数据库

java - 获取映射通过引用应用程序启动时的未知目标实体属性异常