Ad
How Efficient Are Hibernate's Interceptors Compared To Database Triggers?
Since I can't make MySQL to update a column with ON UPDATE, I'm thinking of using Hibernate's interceptors, to update an updated
table each time the row is updated.
My only concern is, how much of a performance penalty does it imply, compared to the ideal case of having MySQL updating it?
Ad
Answer
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
Ad
source: stackoverflow.com
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key
Ad