There's no significant performance penalty and you don't need an interceptor either.
I created an example on GitHub for this.
You need to create a JPA callback listener:
public class UpdatableListener {
@PrePersist
@PreUpdate
private void setCurrentTimestamp(Object entity) {
if(entity instanceof Updatable) {
Updatable updatable = (Updatable) entity;
updatable.setTimestamp(new Date());
}
}
}
which uses an interface that's defined like this:
public interface Updatable {
void setTimestamp(Date timestamp);
Date getTimestamp();
}
You can then define a base class for all your entities:
@MappedSuperclass
@EntityListeners(UpdatableListener.class)
public class BaseEntity implements Updatable {
@Column(name = "update_timestamp")
private Date timestamp;
@Override
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
@Override
public Date getTimestamp() {
return timestamp;
}
}
And then simply have your entities extend it:
@Entity(name = "Post")
@Table(name = "post")
public class Post extends BaseEntity {
...
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public static class PostComment extends BaseEntity {
...
}
When you modify these entities:
doInJPA(entityManager -> {
Post post = entityManager.find(Post.class, 1L);
post.setTitle("Post");
for(PostComment comment : post.getComments()) {
comment.setReview("Review");
}
});
Hibernate will take care of setting the timestamp
column:
UPDATE post
SET update_timestamp = '2016-02-06 17:03:26.759' ,
title = 'Post'
WHERE id = 1
UPDATE post_comment
SET update_timestamp = '2016-02-06 17:03:26.76' ,
post_id = 1 ,
review = 'Review'
WHERE id = 1
UPDATE post_comment
SET update_timestamp = '2016-02-06 17:03:26.76' ,
post_id = 1 ,
review = 'Review'
WHERE id = 2