【问题标题】:Is there a less redundant way to load/save an entity?是否有一种较少冗余的方式来加载/保存实体?
【发布时间】:2019-06-17 15:14:50
【问题描述】:

目前,我们的项目中有很多这种模式。加载实体并在之后保存它是一项非常常见的任务。 Kotlin 中是否有更简洁、更少冗余的方式?

userRepository.findByIdOrNull(1L)?.let {
    userRepository.save(it.apply {
        firstName = "Jon"
        lastName = "Doe"
    })
} ?: throw NoSuchElementException("User not found")

【问题讨论】:

    标签: spring spring-boot jpa kotlin


    【解决方案1】:

    据我所知,没有官方方法可以让它更简洁,但你可以像这样在JpaRepository 上创建一个扩展函数:

    inline fun <reified T : Any, ID : Serializable> JpaRepository<T, ID>.update(id: ID, modify: T.() -> Unit) = findByIdOrNull(id)?.let {
        modify(it)
        saveAndFlush(it)
    } ?: throw NoSuchElementException("There is no ${T::class.simpleName} with id $id!")
    

    并像这样使用它:

    userRepository.update(1L) {
        firstName = "Jon"
        lastName = "Doe"
    }
    

    这将使呼叫站点真正干净简洁。

    update 当然可以返回null 而不是抛出异常。这取决于您的用例。


    如果您想知道为什么我会立即提出并回答这个问题,请查看here

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多