@ManyToOne 关联实体类型错误解决方法
在使用 @ManyToOne 注解创建多对一关系时,特性类型应该为关联实体的主键类型,而不是关联实体本身的类型。
例如,以下代码片段中,detail 的类型为 JadSfdReportApplyEntity,这会导致错误:
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "R_DETAIL_ID")
private JadSfdReportApplyEntity detail;
错误原因:
JPA 无法直接将一个实体对象映射到另一个实体的某个字段。为了建立关系,需要使用主键类型来进行关联。
解决方案:
- 将
detail的类型更改为关联实体的主键类型,通常是Long或Integer。
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "R_DETAIL_ID")
private Long detailId;
- 在关联实体
JadSfdReportApplyEntity中添加一个名为detailId的字段,并将其与主表R_DETAIL_ID列关联起来。
示例:
假设 JadSfdReportApplyEntity 是关联实体,并且它有一个名为 id 的主键字段,则需要添加如下代码:
public class JadSfdReportApplyEntity {
// 其他字段...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
通过以上操作,即可成功建立多对一关系。
注意:
- 关联实体的主键类型应与数据库中关联表的主键类型一致。
- 在代码中,应确保关联实体的
detailId字段与主表的R_DETAIL_ID列对应。
原文地址: https://www.cveoy.top/t/topic/pag3 著作权归作者所有。请勿转载和采集!