4

I would like to update my entity before it gets deleted (because a DB Trigger will use that value later).

So I tried this inside my EntityListener:

    @PreRemove
    void onRemove(Object entity) {
        CurrentUser currentUser = CDI.current().select(CurrentUser.class).get();
        if (currentUser != null && entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            baseEntity.deletedBy = currentUser.userId;
            baseEntity.persistAndFlush();
        }
    }

However, the changes are not persisted to the DB before the deletion - presumably because the deletion transaction is already started.

How can I achieve this ?

Tim
  • 3,910
  • 8
  • 45
  • 80
  • 1
    It seems that the pre-remove lifecycle callback methods run in the same transaction, so in theory yoy should be able to update. I can think of 2 problems though: Maybe Hibernate is smart enough to skip updates on entities that are marked to be deleted, even though you flush. Second, and more serious, even if the update actually happens before the deletion, are you sure the trigger will work? Since the update and the deletion occur in the same transaction, the net result is the deletion only, so if the trigger is on update I *guess* it should not run! – Nikos Paraskevopoulos Oct 14 '21 at 09:41
  • 1
    (continuing from previous) If I had a choice, I would post a message to some kind of queue on deletion, and let the consumer of that message run the trigger logic. And leave the DB free of logic altogether. – Nikos Paraskevopoulos Oct 14 '21 at 09:43
  • I think you are right. I ended up not using the @PreRemove hook. Instead, before deleting the entity, I updated its new field "deleted_by" and then I deleted it. The trigger then can read this new field. Just post your comment as answer, I'll accept it. – Tim Oct 15 '21 at 11:03

0 Answers0