绕过“未找到实体”与JPA错误 [英] Bypass "Entity not found" error with JPA
问题描述
例如,我有一个Person对象,它具有关系到另一个Person对象。
当我删除一个Person时,我不想删除这个Person在她可以拥有的所有关系中,因为有时候这个Person对象不知道它被引用的地方。所以,如果我想清除删除所有引用,我必须做额外的sql工作,可能会导致性能问题。
在理想的世界中,我想删除Person对象和另一个Person对这个Person进行引用时(因为它在它的关系中有它的id),只需返回null。
事实是JPA抱怨
javax.persistence.EntityNotFoundException:不存在具有给定标识符的行
有没有办法强制JPA返回空引用,而不是这种情况下的异常?
您可以使用 @ NotFound 注释,其值 NotFoundAction.IGNORE
,如果关联的实体不存在,将返回null。
谨慎地说:如果你在收藏中使用它而hibernate没有找到其中的一个条目,它会在集合中添加一个空值,这非常烦人。为避免这种情况,您可以将集合包装在跳过空值的集合中。
Sometimes it's quite difficult (or a performance problem) to clean delete all references to an entity.
For example, I've got a Person object which has relationships to another Person objects.
When I delete a Person, I don't want to delete this Person in all relations she can have simply because sometimes this Person object does not know where it is referenced. So, if I would like to clean delete all references, I must do extra sql work that can result in performance problem.
In an ideal world, I would like to delete the Person object and when another Person do a reference to this Person (because it has its id in its relations), simply return null.
The fact is JPA complains that
javax.persistence.EntityNotFoundException: No row with the given identifier exists
Is there a way to force JPA to return a null reference and not an exception in this case ?
You can use the @NotFound annotation with the value NotFoundAction.IGNORE
, which will return null if an associated entity doesn't exist.
A word of caution: if you use this in a collections and hibernate doesn't find one of the entries, it will add a null value in the collection, which is very annoying. To avoid this, you can wrap the collection in a Collection that skips nulls.
这篇关于绕过“未找到实体”与JPA错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!