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

Quarkus升级后缺失@WithSession引发No current Mutiny.Session异常

问题原因

Quarkus 3.x对Hibernate Reactive的会话上下文传播逻辑做了收紧调整:JAX-RS资源方法触发的自动会话仅在当前方法执行边界内有效,跨层调用服务方法时,若服务方法未显式关联上下文,会话不会自动传递。而Quarkus 2.x的隐式跨层上下文传播在3.x中被移除,以更严格地遵循Reactive上下文的边界规则。

解决方案

以下是几种可行的解决方式,按需选择:

1. 给服务类/方法添加@WithSession注解

直接在服务类或其调用仓库的方法上添加io.quarkus.hibernate.reactive.panache.common.WithSession注解,显式声明该方法需要Hibernate Reactive会话上下文:

import io.quarkus.hibernate.reactive.panache.common.WithSession;

@ApplicationScoped
public class YourService {

    @Inject
    YourRepository repository;

    @WithSession
    public Uni<List<YourEntity>> getEntities() {
        return repository.listAll();
    }
}

这个方式和你在仓库方法上加注解的逻辑一致,只是把上下文声明上移到服务层,避免在每个仓库方法重复注解。

2. 使用Reactive事务注解@Transactional

如果你的服务方法涉及多步数据库操作(需要事务保证),可以用io.quarkus.narayana.jta.runtime.interceptor.Transactional注解(Quarkus Reactive事务专用),它会自动管理会话和事务上下文:

import io.quarkus.narayana.jta.runtime.interceptor.Transactional;

@ApplicationScoped
public class YourService {

    @Inject
    YourRepository repository;

    @Transactional
    public Uni<Void> createAndUpdateEntity(YourEntity entity) {
        return repository.persist(entity)
                .chain(() -> repository.updateSomeField(entity.id, "new value"));
    }
}

注意:该注解要求方法返回Uni或Multi类型,否则无法生效。

3. 确保服务方法返回Reactive类型(Uni/Multi)

检查你的服务方法是否返回Uni<T>或Multi<T>:只有返回Reactive类型,Quarkus的上下文传播机制才能将JAX-RS的会话上下文传递到服务层。如果服务方法是同步返回值,上下文会直接中断,导致仓库方法找不到会话。

4. 确认启用上下文传播扩展

确保项目依赖中包含quarkus-smallrye-context-propagation扩展,它负责在Reactive流中传递各种上下文(包括Hibernate会话)。如果没有添加,在pom.xml(Maven)中引入:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-smallrye-context-propagation</artifactId>
</dependency>

这个扩展是Quarkus 3.x中Reactive上下文传播的基础,默认可能未自动引入,需要显式添加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 19:06:19