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

Hibernate映射报错:mappedBy引用未知实体属性求助

问题解决:Hibernate mappedBy引用未知实体属性

错误原因

报错核心是mappedBy指定的属性名与关联实体中的Java属性名不匹配:

org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.application.model.Dipendente.azienda_id in com.application.model.Azienda.listaDipendenti

在Azienda类的@OneToMany注解中,你写的是mappedBy="azienda_id",但Dipendente类中对应的关联属性名是aziendaId(Java驼峰命名),而非数据库列名azienda_id。Hibernate要求mappedBy必须指向关联实体的Java属性名,不是数据库字段名。

另外还存在一个小问题:Azienda类中的setId_azienda方法命名错误,属性是idAzienda,setter应该对应setIdAzienda,否则会导致属性赋值异常。

修复步骤

1. 修正Azienda类的@OneToMany注解

将mappedBy的值从azienda_id改为aziendaId:

@OneToMany(mappedBy="aziendaId", targetEntity=Dipendente.class, fetch=FetchType.LAZY, cascade=CascadeType.ALL)
@JsonManagedReference
private Set<Dipendente> listaDipendenti = new HashSet<>(); 

2. 修正Azienda类的setter方法

把setId_azienda改为setIdAzienda,与属性名匹配:

public void setIdAzienda(Long idAzienda) {
    this.idAzienda = idAzienda;
}

3. 可选优化(避免手动代码错误)

给Azienda类添加@Data注解,让Lombok自动生成正确的getter/setter,替代手动编写的方法,减少人为错误:

@ToString
@Data  // 添加这个注解
@Entity
@Table(name="azienda", schema="negozio")
public class Azienda {
    // ... 其他代码保持不变
}

验证修复

修改完成后,重新启动Spring Boot项目,entityManagerFactory的创建错误应该会消失,JPA关联映射可以正常初始化。

内容的提问来源于stack exchange,提问作者fabio lo guasto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:25:16