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

使用Hibernate @Formula注解获取集合数据的技术问询

JPA多表关联:用@ElementCollection + @Formula映射跨表数据

最近我碰到一个场景——数据库里从实体A到C的关联链上多了几张中间表,没法直接用常规的关联注解搞定,于是我写了这么一段JPA实体映射配置,分享给大家:

@Entity
@Table(name = "a")
class A {
    @Id
    private int id;
    private String title;
    
    @ElementCollection(targetClass=String.class)
    @Formula("(select c.useful_information from A a " + 
             "join B b on a.id = b.a_id " + 
             "join C c on b.id = c.b_id " + 
             "where a.id = id)")
    private List<String> usefulInformation;
    
    // 可按需补充getter/setter方法
}

简单说下这段配置的逻辑:

  • 用@ElementCollection来映射这个字符串列表,因为我们要获取的是C表中单个字符串字段的集合
  • @Formula里写了自定义SQL子查询,通过关联A→B→C三张表,把当前A实例对应的所有C表的useful_information字段值查出来,直接映射到usefulInformation属性上
  • 子查询里的where a.id = id要注意:第二个id是当前A实体的主键字段,JPA会自动替换成当前实例的主键值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:57:22