Hibernate Soft Deletion仍然删除我的记录

时间:2014-07-13 07:44:52

标签: java hibernate orm hibernate-mapping soft-delete

我正在尝试使用Hibernate实现软删除,但出于某种原因我的记录仍然被删除。有人介意看看。

public class SoftDeleteEventListener extends DefaultDeleteEventListener {

private static final long serialVersionUID = 1L;

@SuppressWarnings("rawtypes")
@Override
public void onDelete(DeleteEvent event, Set transientEntities) throws HibernateException {
    Object dbEntity = event.getObject();

    if (dbEntity instanceof Entity) 
    {
        ((Entity)dbEntity).setDeleted(true);
        ((Entity)dbEntity).setDeletedOn(new Date());

        EntityPersister persister = event.getSession().getEntityPersister( event.getEntityName(), dbEntity);
        EntityEntry entityEntry = event.getSession().getPersistenceContext().getEntry(dbEntity);

        cascadeBeforeDelete(event.getSession(), persister, dbEntity, entityEntry, transientEntities);
        cascadeAfterDelete(event.getSession(), persister, dbEntity, transientEntities);
    } else {
        super.onDelete(event, transientEntities);
    }
}

}

这就是我注册会话/听众的方式

Configuration configuration = new Configuration();
        configuration.configure();
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(ssrb.build());

        EventListenerRegistry registry = ((SessionFactoryImpl)sessionFactory).getServiceRegistry().getService(
        EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.DELETE).appendListener(new SoftDeleteEventListener());

1 个答案:

答案 0 :(得分:1)

为什么不依赖于SQLDelete覆盖,就像在this blog post中非常好地解释一样。

  1. 您定义了已删除的列

  2. 您使用

    注释实体
    @SQLDelete(sql="UPDATE customer SET deleted = true WHERE id = ?")
    
  3. 这比使用Hibernate Interceptor要简单得多。

    我会尝试更简单的版本:

    if (dbEntity instanceof Entity) 
    {
        ((Entity)dbEntity).setDeleted(true);
        ((Entity)dbEntity).setDeletedOn(new Date());
    
        event.getSession().mergedbEntity
    } else {
        super.onDelete(event, transientEntities);
    }