Changing state of Entity if only ElementCollection is changed

Hi all,

we’re using the auditing features of spring-data which automatically sets a last updated timestamp. If only a mapped ElementCollection of an entity is changed this does not work as no PreMerge or PrePersist events are raised in such situations.
We worked around it by saving the entity, checking if the timestamp has changed and if not we’re setting it manually and save the entity again. While this works you have to do it for every entity where those situations can arise.

Is it possible to achieve something like that with proprietary Hibernate events?

It tried this:

    @Override
    public void onPreUpdateCollection(PreCollectionUpdateEvent event) {
        var target = event.getAffectedOwnerOrNull();
        if (target instanceof AbstractAuditingEntity) {
            ((AbstractAuditingEntity) target).setTs(LocalDateTime.now());
            event.getSession().merge(target);
        }
    }

But the of value of “ts” is still not updated on the DB. I guess the event handling is to late in the process.

Many thanks,

Daniel

Hi, I don’t think it is possible to change the state anymore when the event is fired. It’s probably best if you introduce add/remove methods on the entity to handle the timestamp change and disallow changing the collection directly.

Yes, we already solved it in this one case like you suggested.

But it’s a huge legacy application so we looked for a more general way.

But thanks for your thoughts.