JPA(休眠)+ Spring:处理唯一的约束冲突 [英] JPA (Hibernate) + Spring: Dealing with unique constraint violations

查看:77
本文介绍了JPA(休眠)+ Spring:处理唯一的约束冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有唯一字段的实体A,该字段基本上定义了该实体,这意味着它相等,然后实体也完全相同.

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.

在重复的情况下,应用程序应静默选择已经存在的实体.现在的问题是,在保存包含As列表的实体时,我应该怎么做.

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.

  • 只要捕捉到异常,然后从那里去

我不确定这是否容易实现,因为DataIntegrityViolationException不会保存任何易于处理的信息,例如在级联的情况下受影响的实体持续存在!!!

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!!!

  • 保存前(保留)检查并用已存在的实体(已设置ID)替换已提交的实体

我更喜欢这种方式,但是会产生相当大的开销,因为对于每个插入,在插入之前可能会有多个选择(存在检查).

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.

什么是更好的方法?

推荐答案

(对于选项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.

对于选项2)(我认为这是标准的JPA/休眠实践),您不仅必须查询并可能从DB加载实体,而且还必须将您的更改从瞬时对象复制到已加载的对象,然后让JPA保存您的更新.这很麻烦,您必须谨慎处理所依赖的所有级联操作,因为您可能需要避免用瞬态对象覆盖持久化对象.JPA/Hibernate没有很好的解决方案,这是一个复杂的问题.

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.

这篇关于JPA(休眠)+ Spring:处理唯一的约束冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆