Best way to detect duplicates when using Spring Hibernate Template

后端 未结 3 1067
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 02:36

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.

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 03:12

    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;
          }
    }
    

提交回复
热议问题