5

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.

Jan
  • 1,594
  • 1
  • 20
  • 30

1 Answers1

6

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.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
slipset
  • 2,960
  • 2
  • 21
  • 17
  • 1
    This reads well, but it doesn't work for me using Hibernate 5.1. I'm trying the same exact thing. For me, the row is still deleted in the end. – Jeff Fairley Apr 09 '17 at 04:11