如何指定JPA中以自定义属性为外键的ManyToOne关联关系
解决方案
你只需要在@ManyToOne注解下方补充@JoinColumn配置即可,具体修改如下:
修改后的Price实体关联部分代码
@ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "supplierCurrencyCode", referencedColumnName = "currencyCode", insertable = false, updatable = false) private ExchangeRate exchangeRate;
参数说明
name = "supplierCurrencyCode":指定当前Price表中用来做关联的外键字段就是你已经声明的supplierCurrencyCodereferencedColumnName = "currencyCode":指定关联的ExchangeRate实体对应的主键字段为currencyCodeinsertable = false, updatable = false:标识这个关联字段不参与持久化的写入、更新操作,避免和你单独声明的supplierCurrencyCode字段产生冲突,后续你只需要给supplierCurrencyCode赋值,关联的exchangeRate会自动映射。
可选优化
如果你没有单独使用supplierCurrencyCode字段的需求,可以直接删除单独声明的private String supplierCurrencyCode;,同时去掉insertable和updatable配置,JPA会自动帮你生成对应的外键字段。
另外注意原代码中private ExchangeRate exchangeRate末尾缺少分号,建议补充避免编译错误。
内容的提问来源于stack exchange,提问作者Vihung
相关产品推荐
相关产品推荐

