小编yez*_*per的帖子

Spring @Transactional 挂起函数

我现在有点沮丧,因为我认为这会容易得多,并且问题会更好地记录下来,但我只是找不到解决方案。因此我在这里寻求帮助。

我正在开发一个 Kotlin 项目,该项目利用 spring boot 版本 2.5.3 并使用 spring data jpa 进行数据库访问和模式定义。非常常见且直接。现在假设我们有某种UserService方法,其中包含一个方法updateUsername,该方法获取 ausername作为参数,并在通过外部服务验证其有效性后更新用户名。为了演示该问题,我想强调一下,在验证用户名之前,我们将用户名手动设置为"foo"。整个工作单元应该在事务中发生,这就是该方法用 注释的原因@Transactional。但由于调用外部服务,当我们等待 http 响应时,该方法将挂起(注意suspend这两个方法上的关键字)。

@Service
class UserService(private val userRepository: UserRepository) {
    @Transactional
    suspend fun setUsername(id: UUID, username: String): Person {
        logger.info { "Updating username..." }
        val user = userRepository.findByIdentityId(identityId = id)
            ?: throw IllegalArgumentException("User does not exist!")

        // we update the username here but the change will be overridden after the verification to the actual …
Run Code Online (Sandbox Code Playgroud)

spring spring-data-jpa kotlin spring-boot kotlin-coroutines

6
推荐指数
1
解决办法
4552
查看次数