Denis Denis
Denis Denis

Reputation: 77

Spring data jpa events: how to make an event only when a specific field changes?

I have an entity:

@Entity
@Audited
@EntityListeners(AuditListener.class)
public class Ticket {

    @Id
    @GeneratedValue
    Long id;

    String address;

    int price;
}

There is a class that listens for changes:

@Component
public class AuditListener {

    @PostUpdate
    private void beforeAnyOperation(Object object) {
        System.out.println(object.toString());
    }
}

I need to implement one of two options:

a) Make the listener react only to changes in the specific field, in my case it's price

b) Make it so that the post update method receives two entities, the updated and the old

How can I implement this?

P.S

I'm also interested in how to make the transaction commit before the post_update method

Upvotes: 1

Views: 795

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16400

What you want is not directly possible. You will need a Hibernate interceptor to get access to the old and new state in an implementation of a onFlushDirty method. With that, you determine if the price changed and remember the object somehow e.g. add to a list in the interceptor. You can then also implement a afterTransactionCompletion method to process the changed objects after a TX completes. Note though, that the TX might commit on the DB but that method is not called i.e. there are no transactional guarantees.

Upvotes: 2

Related Questions