JPA (Hibernate) + Spring: Dealing with unique constraint violations

大憨熊 提交于 2021-02-10 20:26:21

问题


I have a entity A with a unique field and that field basically defines the entity, meaning it it is equal then then entity is also exactly the same.

A second point is that it is lets say in no way exceptional if that constraint is violated. Meaning it is fully expected that users will try to input duplicates.

In case of duplicate, the application should silently chose the already existing entity. My question is now what I should do especially when saving entities containing a list of As.

  • just catch the exception and go from there

I'm not sure this is that easily possible as DataIntegrityViolationException doesn't hold any easily processable information like what entity was affected in case of Cascaded persist!!!

  • Check before save (persist) and replace submitted entity with existing one (that has an id set)

I like this more however there is a considerable overhead because then there are possibly multiple selects (existence checks) before an insert for every single insert.

What is the better approach?


回答1:


for option 1) you are looking for something like http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html but there is nothing equivalent at JPA/hibernate level for that command (I don't think that's ANSI SQL). Trying to catch the exception and "go from there" is a bad idea because transactions will get rolled back and you will have to go through many problems to make it behave like you want.

For option 2), which I believe is the standard JPA/hibernate practice, you will not only have to query and possibly load the entity from DB, but also copy your changes from your transient object to the loaded object and then let JPA to save your updates. This is quite a hassle and you will have to be careful with any cascade operations that you are relying on, because you will probably need to avoid overwriting persisted objects with transient ones. It is a complicated problem for which JPA/Hibernate has no good solution.



来源:https://stackoverflow.com/questions/15731297/jpa-hibernate-spring-dealing-with-unique-constraint-violations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!