与数据库触发器相比,Hibernate的拦截器效率如何?

时间:2016-02-05 17:12:43

标签: mysql database performance hibernate triggers

I can't make MySQL to update a column with ON UPDATE以来,我正考虑使用Hibernate's interceptors,每次更新行时都更新updated表。

我唯一担心的是,与MySQL更新它的理想情况相比,它意味着多少性能损失?

1 个答案:

答案 0 :(得分:1)

没有明显的性能损失,你也不需要拦截器。

我为此创建了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());
        }
    }

}

使用如下定义的接口:

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