Search code examples
javajpaentitymanager

Why calling EntityManager.merge method with @PreUpdate does't return updated entity?


I want to update my Entity.

I'm using JPA and I'm calling EntityManger.merge method. The Entity is annotated with @PreUpdate annotation, which sets the system Date in the Entity.

This is the DAO's method I call to execute update:

@PersistenceContext(unitName = "myPersistentUnit")
protected EntityManager em;

@Override
public T update(T entity) throws MyException {
    try {
        return em.merge(entity);
    } catch (Exception e) {
        throw new MyException(e);
    }
}

This is the Entity I want to update:

@Entity
@Table(name = MyEntity.TABLE_NAME)
public class MyEntity {

    public static final String TABLE_NAME = "MY_TABLE_NAME";

        // other properties

    @Column(name = "TIMESTAMP_LAST_UPDATE", nullable = true)
    @Temporal(TemporalType.TIMESTAMP)
    private Date timestampLastUpdate;

    @PreUpdate
    public void preUpdate() {
        this.setTimestampLastUpdate(new Date());
    }

        // getters and setters

}   

I expect that the DAO's method

return em.merge(entity)

returns updated entity, with updated property "timestampLastUpdate", but it isn't so.


Solution

  • The callbacks are executed before or after the SQL statements are sent to the database.

    Merge does not trigger a flush to execute the statements. You have to execute EntitiyManager.flush() if you wan to trigger the listeners.