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

JPA/Hibernate基于非主键列关联两张表出现MappingException如何解决

问题根因
  • @JoinColumn 配置映射规则错误:@ManyToOne 注解声明在Foo实体(对应skl_transactions表)中,name属性需填写当前表的关联字段名,referencedColumnName需填写关联目标表的关联字段名。你之前的配置将两个参数值写反,导致Hibernate在merchant_config表中查找不存在的column_a字段,抛出映射异常。
  • @OneToMany的mappedBy属性值配置错误:该属性需要填写对方实体中对应的关联属性名,也就是Foo实体中定义的merchant属性,而非表名merchant_config。
修正后代码
@Entity
@Table(name = "skl_transactions")
public class Foo implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Basic(optional = false)
    protected Long id;

    @Column(name = "column_a")
    private String senderAddress;

    // 修正@JoinColumn配置:name是当前表的关联列column_a,referencedColumnName是对方表的关联列column_b
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="column_a", referencedColumnName = "column_b", insertable = false, updatable = false)
    private Bar merchant;

    // getters and setters
}

@Entity
@Table(name = "merchant_config")
public class Bar implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Basic(optional = false)
    protected Long id;

    // 若column_b值唯一建议加unique约束,避免关联匹配到多条数据
    @Column(name = "column_b", unique = true)
    private String merchantAddress;

    // 修正mappedBy值为对方实体的关联属性名merchant
    @OneToMany(mappedBy = "merchant", fetch = FetchType.LAZY)
    private List<Foo> transactions = new ArrayList<>();

    // getters and setters
}
补充说明
  • 上述@JoinColumn中添加了insertable = false, updatable = false参数,是为了避免关联字段被重复映射,如果你需要通过Foo实体同时维护column_a的值,保留该配置即可。
  • 如果需要查询Foo时自动加载关联的Bar信息,可将@ManyToOne的fetch属性改为FetchType.EAGER,或者在查询时使用join fetch语句主动关联加载,避免懒加载额外触发查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:42:01