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
相关产品推荐
相关产品推荐

