Search code examples
javajpasql-updatejpql

PreUpdate listener triggered during empty update


I have an entity with the last modified attribute:

@Temporal(TemporalType.TIMESTAMP)
private Date lastModified;

@PreUpdate
@PrePersist
protected void onUpdate() {
    lastModified = new Date();
}

and a named jpql update query, which sets some attributes for old entities:

update entity e set ... where e.lastModified < :threshold

The onUpdate() method is however called even for entities, which has not been modified, that is event if:

entityManager.createQuery("...").executeUpdate();

returns zero as the number of updated entities.

Can I update only the old entities without touching the recent ones? The threshold parameter is not known in the updated entity, so I cannot move the update into onUpdate() method. Can native query help me in this?


Solution

  • Why don't you replace the @PreUpdate/@PrePersist mechanism with a @Version on the lastModified field ? This way all updated entity will have the field set (and only updated ones).

    It should make the job as you expect if I understood well your case.