二十一、Spring boot中Jpa持久化监听器,拦截增删改查

  在JPA中,我们使用Java Persistence API进行数据的持久化(增删改查),相应的该API也提供了监听数据持久化生命周期中的回调方法,主要由以下几个注解来实现:
* @PrePersist 保存前
* @PostPersist 保存后
* @PreRemove 删除前
* @PostRemove 删除后
* @PreUpdate 更新前
* @PostUpdate 更新后
* @PostLoad 查询后
  这些注解必须配合@EntityListeners注解来使用,@EntityListeners注解就是实体监听器注解。
  我们以监听保存Customer对象为例:
第一步:创建监听器类CustomerListener

public class CustomerListener {
    /**
     * 在保存之前调用
     */
    @PrePersist
    public void prePersist(Object source){
        System.out.println("@PrePersist:" + source);
    }
    /**
     * 在保存之后调用
     */
    @PostPersist
    public void postPersist(Object source){
        System.out.println("@PostPersist:" + source);
    }
}


第二步:在Customer类上加@EntityListeners注解

@EntityListeners(value = {CustomerListener.class})
public class Customer {
}

  通过以上,即可拦截数据持久化

猜你喜欢

转载自blog.csdn.net/panchang199266/article/details/82903714