Video in progress

Strong Middle 🐻 Hibernate and JPA

To send an event after an entity is saved, would you use `@PostPersist` or `@TransactionalEventListener`?

@PostPersist is called when the INSERT is executed or scheduled, but the transaction hasn't committed yet, so if it rolls back, the event has already gone out. @TransactionalEventListener(phase = AFTER_COMMIT) runs only after a successful commit, so it's the right place for external side effects (email, Kafka).

📖 Answer

The wrong version:

@Entity
@EntityListeners(OrderListener.class)
class Order { ... }

class OrderListener {
    @PostPersist
    void sent(Order o) {
        mailer.send(o.getCustomerEmail(), "Buyurtmangiz qabul qilindi"); // the transaction is still open
    }
}

The problems: if a later step hits a constraint error and rolls back, the customer gets an email about an order that doesn't exist. With IDENTITY, @PostPersist is called right after the INSERT, and with SEQUENCE it can even be called before the flush, so the timing isn't precise. Slow I/O inside the listener holds the transaction and the connection. And working with the EntityManager inside a JPA callback is restricted by the specification too.

The right version:

@Transactional
public Order create(CreateOrder cmd) {
    Order o = repo.save(new Order(cmd));
    events.publishEvent(new OrderCreated(o.getId()));
    return o;
}

@Component
class OrderMailer {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    void on(OrderCreated e) { mailer.sendCreated(e.orderId()); }
}

The event runs after the commit. But there's a catch: if the application crashes after the commit and before the listener runs, the event is lost. For important messages like Kafka that isn't enough, and you need an outbox table. For things like email or cache eviction, where losing one is tolerable, AFTER_COMMIT is enough.

I use @PostPersist only for simple things inside the entity: a log line, a computed field, a metric.