双向 `@OneToMany` 中“mappedBy”放错端会导致什么 SQL 异常?
解读
国内一线/二线互联网公司的面试官常把“mappedBy 写反”作为区分初中级与高级 ORM 工程师的试金石。
场景:
- 实体 A(一)与实体 B(多)双向关联;
- 本应把 mappedBy 写在
@OneToMany端,让@ManyToOne端拥有外键列; - 候选人却把 mappedBy 写在
@ManyToOne端,或干脆两端都写 mappedBy。
结果:Hibernate 在启动期无法决定谁负责维护外键列,于是抛出映射异常;若侥幸启动成功,运行时也会因重复外键更新而触发数据库级约束冲突。面试官期待你准确说出异常关键字、堆栈特征与根因,并给出修复方案。
知识点
- mappedBy 语义:只在“反向端”出现,声明“本端不控制外键,由对端属性名所指字段维护”。
- 物理模型规则:关系型数据库一张外键列只能由一方维护;ORM 必须保证唯一“主控方”。
- Hibernate 启动校验:
- 若两端都出现 mappedBy →
org.hibernate.AnnotationException: Referenced property not found in mapped class或Illegal use of mappedBy on both sides; - 若
@ManyToOne端写 mappedBy →mappedBy reference an unknown target entity property;
- 若两端都出现 mappedBy →
- 运行时 SQL 异常:若侥幸绕开校验,Hibernate 会生成两条互为冲突的 update 语句,导致
MySQLIntegrityConstraintViolationException: Duplicate entry 'xxx' for key 'PRIMARY'或ORA-02291: integrity constraint violated – parent key not found。 - 正确范式:“一”方用
@OneToMany(mappedBy = "..."),“多”方用@ManyToOne @JoinColumn,保证外键列落在多表,符合数据库范式与性能习惯。
答案
把 mappedBy 放错端后,Hibernate 在启动期就会抛出 AnnotationException,典型信息:
org.hibernate.AnnotationException: Unknown mappedBy value 'xxx' in ...
或
Illegal use of mappedBy on both sides of the relationship。
若框架未拦截,运行时会出现重复外键插入/更新,数据库返回 Duplicate entry 或 integrity constraint violated 等 SQL 异常。
根本原因是外键列归属冲突,ORM 无法确定唯一维护方。
修复:把 mappedBy 只写在 @OneToMany 端,并确保 @ManyToOne 端使用 @JoinColumn 承担外键责任。
拓展思考
- JPA 2.2 规范并未强制启动期校验,Spring Boot 2.7+ 配合 Hibernate 5.6 已做提前 fail-fast;了解源码可定位
org.hibernate.cfg.annotations.TableBinder#handleFkSecondPass。 - 云原生分库分表场景(ShardingSphere、MyCat)对“外键列唯一维护”要求更严,mappedBy 写反会导致路由键无法对齐,出现跨库更新失败。
- 性能角度:正确写法可启用 Hibernate 批处理与二级缓存;反向端加
@OneToMany(mappedBy)并标记fetch = LAZY,能避免 N+1。 - 面试追问:若面试官继续问“是否可以不使用 mappedBy”,可答“退化为单向双向各维护一次外键,但会冗余列且需额外同步,生产环境禁止”。