You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用@Transactional时,Spring Data JPA查询实体是否处于托管状态?

Spring Data JPA 无事务下查询返回的实体是否处于托管状态?

我使用Spring Data JPA 3.2.2版本的JpaRepository,查看实现后发现它通过jakarta.persistence.EntityManager执行find操作。我了解到调用EntityManager.find会将实体纳入持久化上下文的托管状态,但又听说实体仅在事务环境下才会进入持久化状态。

我想确认以下代码中,查询返回的实体是否能保证处于托管状态?

Controller代码

@GetMapping("individual/check")
fun getIndividualaccountCreateEligibility(
    @RequestAttribute actor: Actor,
): Response<Boolean> {
    return Response(
        data = accountService.canCreateIndividualAccount(
            actor.user?.id,
        ),
    )
}

Service代码

fun canCreateIndividualAccount(userId: Long?): Boolean {
    val accounts: List<AccountEntity>
    if (userId != null) {
        accounts = accountRepository.findAllByUserId(userId)
    } else {
        return false
    }

    val ownerAccountIds = accounts
        .filter { it.isOwner }
        .map { it.accountInfo.id }

    return AccountInfoRepository.findAllById(ownerAccountIds)
        .none() { it.isIndividual() && it.deletedAt == null } 
}

我原本认为即使不使用@Transactional注解,执行查询操作后实体也会处于托管状态,但同事告知无@Transactional时实体处于分离状态。

内容的提问来源于stack exchange,提问作者ramason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 15:31:09