读取实体时更改 DAO/Repository 中的特定值

我正在从旧的遗留数据库中读取数据。不知何故,他们使用 0 索引放置所有不存在的关系,例如:Object Person:


id: 123

name: john

surname: snow

birthCityId: 0 <-- this means that there is no relationship between city and this person.

现在,在 JPA 中,我遇到的问题是它正在加载人员实体,但找不到索引为 0 的相关城市实体。我想编写代码,当我有 ID 为 0 的城市时,城市实体设置为空。我怎样才能做到这一点?我不想在数据库中创建索引为 0 的新实体。


繁花不似锦
浏览 98回答 2
2回答

白衣染霜花

您可以使用 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 加载时会发生异常,即在您能够通过其他方式处理它之前。

慕斯王

我假设你有Person{@Many2One @JoinColumn("birthCityId") City birthCity;...}最简单的解决方案是在 city 中添加 id=0 的表行,其余为空这给你的班级@PostLoadpublic viod cityInit(){&nbsp; &nbsp;if(birthCity!=null&&birthCity.getId()==0){&nbsp; &nbsp; &nbsp; birthCity==null;&nbsp; &nbsp;}}有更优雅的解决方案,但这将使您快速入门
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java