自 I can't make MySQL to update a column with ON UPDATE ,我正在考虑使用 Hibernate's interceptors ,每次更新行时都会更新 updated
表。
我唯一关心的是,与让 MySQL 更新它的理想情况相比,这意味着多少性能损失?
最佳答案
不会有明显的性能损失,而且您也不需要拦截器。
我创建了一个example on GitHub为此。
您需要创建一个 JPA 回调监听器:
public class UpdatableListener {
@PrePersist
@PreUpdate
private void setCurrentTimestamp(Object entity) {
if(entity instanceof Updatable) {
Updatable updatable = (Updatable) entity;
updatable.setTimestamp(new Date());
}
}
}
它使用如下定义的接口(interface):
public interface Updatable {
void setTimestamp(Date timestamp);
Date getTimestamp();
}
然后您可以为所有实体定义一个基类:
@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;
}
}
然后只需让您的实体扩展它即可:
@Entity(name = "Post")
@Table(name = "post")
public class Post extends BaseEntity {
...
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public static class PostComment extends BaseEntity {
...
}
当您修改这些实体时:
doInJPA(entityManager -> {
Post post = entityManager.find(Post.class, 1L);
post.setTitle("Post");
for(PostComment comment : post.getComments()) {
comment.setReview("Review");
}
});
Hibernate 将负责设置 timestamp
列:
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
关于mysql - 与数据库触发器相比,Hibernate 的拦截器效率如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35229784/