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

如何在Quarkus中关联三张表并获取嵌套JSON数据?

在Quarkus中实现Client-Commands-Articles三级关联查询

1. 完善实体类的关联映射

你已经完成了Client与ClientCmd的一对多关联,接下来需要在ClientCmd和Article之间建立关联,让Client能通过ClientCmd间接获取对应的Articles:

ClientCmd实体添加关联

public class ClientCmd {
    // 已有字段...
    @ManyToOne
    @JoinColumn(name = "client_id")
    // 标记为反向引用,避免JSON序列化循环问题
    @JsonBackReference
    private Client client;

    // 添加与Article的一对多关联
    @OneToMany(mappedBy = "clientCmd", fetch = FetchType.LAZY)
    // 标记为正向引用,主动序列化该属性
    @JsonManagedReference
    private List<Article> articles;

    // getter、setter方法...
}

Article实体添加关联

public class Article {
    // 已有字段...
    @ManyToOne
    @JoinColumn(name = "client_cmd_id")
    // 标记为反向引用,避免循环序列化
    @JsonBackReference
    private ClientCmd clientCmd;

    // getter、setter方法...
}

2. 实现关联数据的查询

JPA默认采用懒加载,直接查询Client可能无法获取嵌套的Articles数据,推荐两种可靠的解决方式:

方式一:使用JPQL的Fetch Join

通过Fetch Join一次性加载所有层级的关联数据,避免N+1查询问题:

@ApplicationScoped
public class ClientRepository implements PanacheRepository<Client> {
    public Client findClientWithCommandsAndArticles(Long clientId) {
        return find("SELECT c FROM Client c JOIN FETCH c.clientCmdList cmd JOIN FETCH cmd.articles WHERE c.id = ?1", clientId)
                .firstResult();
    }
}

方式二:使用实体图(EntityGraph)

定义实体图指定要加载的关联属性,灵活性更高:

@Entity
@NamedEntityGraph(name = "Client.withCommandsAndArticles",
        attributeNodes = {
                @NamedAttributeNode(value = "clientCmdList", subgraph = "clientCmd.articles")
        },
        subgraphs = {
                @NamedSubgraph(name = "clientCmd.articles", attributeNodes = @NamedAttributeNode("articles"))
        })
public class Client {
    // 已有代码...
    @OneToMany(mappedBy = "client")
    @JsonManagedReference
    private List<ClientCmd> clientCmdList;
}

查询时调用该实体图:

public Client findClientWithCommandsAndArticles(Long clientId) {
    return find("#Client.withCommandsAndArticles", clientId)
            .firstResult();
}

3. 验证JSON输出

完成配置后,查询单个Client返回的JSON会自动包含嵌套层级数据,结构示例:

{
  "id": 1,
  "name": "测试客户",
  "clientCmdList": [
    {
      "id": 101,
      "cmdName": "订单001",
      "articles": [
        {
          "id": 201,
          "title": "商品A"
        },
        {
          "id": 202,
          "title": "商品B"
        }
      ]
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:25:36