我正在從舊的遺留數據庫中讀取數據。不知何故,他們使用 0 索引放置所有不存在的關系,例如:Object Person:id: 123name: johnsurname: snowbirthCityId: 0 <-- this means that there is no relationship between city and this person.現在,在 JPA 中,我遇到的問題是它正在加載人員實體,但找不到索引為 0 的相關城市實體。我想編寫代碼,當我有 ID 為 0 的城市時,城市實體設置為空。我怎樣才能做到這一點?我不想在數據庫中創建索引為 0 的新實體。
2 回答

白衣染霜花
TA貢獻1796條經驗 獲得超10個贊
您可以使用 Hibernate@NotFound注釋:
@ManyToOne
@NotFound(action=NotFoundAction.IGNORE)
private City birthCity;
https://docs.jboss.org/hibernate/orm/5.3/javadocs/index.html?org/hibernate/annotations/NotFound.html
我沒有看到其他已發布的解決方案工作,因為在 Hibernate 加載時會發生異常,即在您能夠通過其他方式處理它之前。

慕斯王
TA貢獻1864條經驗 獲得超2個贊
我假設你有
Person{
@Many2One @JoinColumn("birthCityId") City birthCity;
...}
最簡單的解決方案是在 city 中添加 id=0 的表行,其余為空
這給你的班級
@PostLoad
public viod cityInit(){
if(birthCity!=null&&birthCity.getId()==0){
birthCity==null;
}
}
有更優雅的解決方案,但這將使您快速入門
添加回答
舉報
0/150
提交
取消