Hibernate:用继承覆盖sql-delete

时间:2011-03-23 12:05:34

标签: java hibernate soft-delete

我有一个实体AB extends A,并尝试使用联接的继承策略进行软删除。

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@SQLDelete("UPDATE A SET deleted = 1 WHERE id = ?")
A {

    @Id long id;
    boolean deleted;
}

@Entity
B extends A {}

似乎Hibernate正确地将表A设置为deleted = 1,但也删除了表B中的整个条目。当然,我想保留这个条目。

有关于此的任何想法吗?

我正在使用Hibernate 3.5.5和基于注释的实体定义。尝试了Hibernate 3.6.2。

1 个答案:

答案 0 :(得分:5)

您想要创建一个DeleteEventListener:

public class SoftDeleteEventListener extends DefaultDeleteEventListener {

private static final long serialVersionUID = 1L;

@Override
public void onDelete(DeleteEvent event, Set arg1) throws HibernateException {
    Object o = event.getObject();
    if (o instanceof SoftDeletable) {
        ((SoftDeletable)o).setStatusId(1);
        EntityPersister persister = event.getSession().getEntityPersister( event.getEntityName(), o);
        EntityEntry entityEntry = event.getSession().getPersistenceContext().getEntry(o);
        cascadeBeforeDelete(event.getSession(), persister, o, entityEntry, arg1);

        cascadeAfterDelete(event.getSession(), persister, o, arg1);

    } else {
        super.onDelete(event, arg1);
    }
}

}

将它挂钩到你的persistence.xml中,就像这样

<property name = "hibernate.ejb.event.delete" value = "org.something.SoftDeleteEventListener"/> 

另外,不要忘记在注释中更新您的级联。