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.
We have an application which needs to detect duplicates in certain fields on create.
Share
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)