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.
It is better to check if data is present in the database. One easy way to check if the data already exists in the database is to have your classes implement Hibernate LifeCyle api. Hibernate allows you to do validate behavior before saving but after an identity is associated with the bean. If certain logic is violated or fails, then save 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 beans = query.list();
if (beans != null && !beans.isEmpty()) {
// This does not save the identity.
return VETO;
}
return NO_VETO;
}
}