开发者

Bypass "Entity not found" error with JPA

开发者 https://www.devze.com 2023-03-29 14:55 出处:网络
Sometimes it\'s quite difficult (or a performance problem) to clean delete all references to an entity.

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 lik开发者_StackOverflowe 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.


No, at least nothing standard (JPA)

But you can control what happens with these association using the cascade attribute ot @*ToMany and @*ToOne annotations.


You'd use @NotFound(action=NotFoundAction.IGNORE) this will skip null entities. BUT (as Augusto said) if you are using for example Primefaces Datatable and get 10 rows and skipped 2, because of the @NotFound(action=NotFoundAction.IGNORE) in your property, you will have 10 rows and not 8 (ghost rows actually).

@NotFound(action=NotFoundAction.IGNORE)
private Product p;


ERROR 1452: Cannot add or update a child row: a foreign key constraint fails....
   if this type of error occur :
   then
  First of all
  goto this table and check in setting > if Engine is: InnoDB then change its to MyISAM

 (and delete references foreign constraint)

Its 100% working...

0

精彩评论

暂无评论...
验证码 换一张
取 消