Is it possible to update some column before every flush to database? I have modifiedOn
and modifiedBy
columns and want to update them on every DB update, similar to DB trigger. Is it possible with JPA?
Asked
Active
Viewed 1,411 times
2 Answers
1
Disclaimer: The following works only with Hibernate / JPA.
You can update the modifiedOn
property like this with JPA:
public class Entity {
private Date modifiedOn;
@PreUpdate
@PrePersist
public void updateModified() {
modifiedOn = new Date();
}
}
As for the modifiedBy
, it is a little bit trickier since the JPA spec discourages references to other entities in the lifecycle callback methods. Furthermore, you would need some knowledge of the current user, which probably belongs to the service layer.
You could use an EntityListener
like this (however, this still uses the callback methods)
@Entity
@EntityListeners({MyListener.class})
public class MyEntity {
Date modifiedOn;
User modifiedBy;
...
}
An in the EntityListener:
public class MyListener {
CurrentUserProvider provider; // Implement this and make sure it is set
@PreUpdate
@PrePersist
public void updateModifier(MyEntity entity) {
entity.setModifiedOn(new Date());
entity.setModifiedBy(provider.getCurrentUser());
}
}

RJo
- 15,631
- 5
- 32
- 63
-
1I read it does not work in EclipseLink, which I currently use. See here: http://stackoverflow.com/a/1877631/952135 – Oliv Dec 14 '12 at 11:11
-
This is how we do it on JPA2.0+Hibernate+Spring. Not sure if EclipseLink supports it. – RJo Dec 14 '12 at 11:14
-
1I tested it, it does not work in EclipseLink. I think it is a bug of eclipselink, that even the modifiedOn does not work, it should according to the JPA spec. The fact that modifiedBy works in Hibernate is an Hibernate extension. I know some internals of Hibernate while I was working with it (not using JPA), I think you can change the reference of "this" object, but changing other object may on may not work depending on the order of processed updates. Please state that this works only for Hiberante and I will mark your answer as correct. – Oliv Dec 17 '12 at 09:19
-1
Obviously JPA has Entity callbacks defined in the spec such as @PrePersist, @PreUpdate. Simple revision of the spec would give you more details

DataNucleus
- 15,497
- 3
- 32
- 37