Reputation: 424
I'm trying to implement soft deletion using Hibernate but for some reason my record still gets deleted. Anyone mind taking a look.
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);
}
}
}
and this is how i am registering my session / listener
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());
Upvotes: 3
Views: 1905
Reputation: 153780
To fix this issue:
You need to define a deleted
column
And, you need to annotate the entity with
@SQLDelete(sql="UPDATE customer SET deleted = true WHERE id = ?")
This is much more simple than using a Hibernate Interceptor.
I'd try a simpler version:
if (dbEntity instanceof Entity)
{
((Entity)dbEntity).setDeleted(true);
((Entity)dbEntity).setDeletedOn(new Date());
event.getSession().mergedbEntity
} else {
super.onDelete(event, transientEntities);
}
Upvotes: 1