我正在从旧的数据库读取数据。不知何故,他们使用 0 索引放置所有不存在的关系,例如: 对象人:
id: 123
name: john
surname: snow
birthCityId: 0 <-- this means that there is no relationship between city and this person.
现在,在 JPA 中,我遇到的问题是它正在加载人员实体,但找不到索引为 0 的相关城市实体。我想编写代码,当我的城市 ID 为 0 时,城市实体设置为 null。 我怎样才能做到这一点? 我不想在数据库中创建索引为 0 的新实体。
谢谢
最佳答案
您可以使用 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 加载时会发生异常,即在您能够通过其他方式处理它之前。
关于java - 读取实体时更改 DAO/Repository 中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993533/