使用Spring Hibernate模板时检测重复的最佳方法 [英] Best way to detect duplicates when using Spring Hibernate Template

查看:87
本文介绍了使用Spring Hibernate模板时检测重复的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个应用程序需要在创建时检测某些字段中的重复项。我们使用Hibernate作为持久层,并使用Spring的HibernateTemplate。我的问题是,在创建之前是否为这个项目进行前期查找更好,或者试图捕获DataIntegrityViolation异常,然后检查这是否是由重复项导致。

它取决于重复是否是特殊情况或业务逻辑情况。

例如,在检查期间检查唯一的电子邮件/用户名注册是一个商业逻辑的案例,检查应该在尝试插入之前完成



如果您需要通过唯一约束指出哪个字段完全失败,最好事先检查一下,而不是抓住例外。捕捉异常并不会给你重要的细节 - 哪个字段失败。



根据异常情况,有许多方法可以获取这些信息,但它非常乏味并且是特定于数据库的(查找数据库中的约束名称(特定于数据库),获取它应用的字段,使字段与实体属性匹配)

We have an application which needs to detect duplicates in certain fields on create. We are using Hibernate as our persistence layer and using Spring's HibernateTemplate. My question is whether it is better to do so an upfront lookup for the item before creating, or to attempt to catch the DataIntegrityViolation exception and then check if this is caused by a duplicate entry.

解决方案

It depends on whether having a duplicate is an exceptional scenario, or a business-logic case.
For example, checking for unique email/username during registration is a business-logic case and the check should be done before trying to insert

If you are required to indicate which field exactly has failed with the unique constraint, you'd better check it beforehand, rather than catching the exception. Catching the exception doesn't give you the important detail - which field has failed.

There are ways to obtain this information, based on the exception, but it is very tedious and is database-specific (lookup the constraint name in the DB (db-specific), get the field it is applied on, match the field with the entity property)

这篇关于使用Spring Hibernate模板时检测重复的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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