Best way to detect duplicates when using Spring hibernation pattern

We have an application that should detect duplicates in certain fields when creating. We use Hibernate as our persistence level and using the Spring HibernateTemplate. My question is whether it is better to do a preliminary search of the item before creating it, or try to catch a DataIntegrityViolation exception, and then check if this is caused by a duplicate record.

+4
source share
3 answers

It depends on whether the duplicate is an exceptional scenario or a business logic case.
For example, checking a unique email / username during registration is a business logical case, and verification must be completed before trying to insert

If you need to specify which field was executed with a unique constraint, it is better to check it beforehand rather than catch the exception. Catching an exception does not give you important information - in which field it was not executed.

There are ways to get this information based on an exception, but it is very tedious and specific to the database (find the name of the constraint in the database (taking into account the specific database), get the field to which it is applied, correspond to the field with the entity property)

+9
source

It is better to check the availability of data in the database. One easy way to check if data exists in a database is to implement your Hibernate LifeCyle api classes. Hibernate allows you to perform a behavior check before saving, but after the identifier is associated with a bean. If a certain logic is violated or not executed, then saving the operation can be vetoed.

public class Bean extends Serializable implements org.hibernate.classic.LifeCycle { public boolean onSave(Session s) { Query query = session.createQuery(from Bean b where b.field=:field"); query.setParameters("field", this.field); @SuppressWarnings("unchecked") List<Bean> beans = query.list(); if (beans != null && !beans.isEmpty()) { // This does not save the identity. return VETO; } return NO_VETO; } } 
+4
source

I definitely agree with the answer of God. I think that's for sure. A similar problem exists within the framework of the project that I am currently working on. We exchange information between several filter-based servers, and there may be scenarios in which the received objects are already added to the database, so a PK exception will occur.

In our case, these PC conflicts are very rare, so we consider this situation exceptional. We also use spring and hibernation to separate these issues, and due to Springs transaction definitions, we use AOP to catch a specific DataIntegrity exception and restart the transaction by performing the necessary integrity checks on demand. I could elaborate on this if you need help using the ExceptionHandlerAdvice.

+1
source

Source: https://habr.com/ru/post/1309084/


All Articles