开发者

Hibernate: Overwrite sql-delete with inheritace

开发者 https://www.devze.com 2023-02-19 00:13 出处:网络
I have an entity A and B extends A and try to have a soft-delete with joined inheritance strategy. @Entity

I have an entity A and B extends A and try to have a soft-delete with joined inheritance strategy.

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

    @Id long id;
    boolean deleted;
}

@Entity
B extends A {}

It seems that Hibernate properly sets the table A to deleted = 1, but also deletes the whole entry from table B. I would, of course, like to preserve this entry.

Any ideas 开发者_开发知识库on that?

I'm using Hibernate 3.5.5 and annotation-based entity definition. Tried Hibernate 3.6.2 as well.


You'd want to create a DeleteEventListener as such:

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

}

hook it into your persistence.xml like this

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

Also, don't forget to update your cascades in your annotations.

0

精彩评论

暂无评论...
验证码 换一张
取 消