当前位置: 移动技术网 > IT编程>开发语言>Java > JPA中EntityListeners注解的使用

JPA中EntityListeners注解的使用

2019年01月09日  | 移动技术网IT编程  | 我要评论

使用场景

entitylisteners在jpa中使用,如果你是mybatis是不可以用的

它的意义

对实体属性变化的跟踪,它提供了保存前,保存后,更新前,更新后,删除前,删除后等状态,就像是拦截器一样,你可以在拦截方法里重写你的个性化逻辑。

它的使用

定义接口,如实体追踪

/**
 * 数据建立与更新.
 */
public interface dataentity {

  timestamp getdatecreated();

  void setdatecreated(timestamp datecreated);

  timestamp getlastupdated();

  void setlastupdated(timestamp lastupdated);

  long getdatecreatedon();

  void setdatecreatedon(long datecreatedon);

  long getlastupdatedon();

  void setlastupdatedon(long lastupdatedon);

}

定义跟踪器

@slf4j
@component
@transactional
public class dataentitylistener {
  @prepersist
  public void prepersist(dataentity object)
      throws illegalargumentexception, illegalaccessexception {
    timestamp now = timestamp.from(instant.now());
    object.setdatecreated(now);
    object.setlastupdated(now);
    logger.debug("save之前的操作");
  }

  @postpersist
  public void postpersist(dataentity object)
      throws illegalargumentexception, illegalaccessexception {

    logger.debug("save之后的操作");
  }

  @preupdate
  public void preupdate(dataentity object)
      throws illegalargumentexception, illegalaccessexception {
    timestamp now = timestamp.from(instant.now());
    object.setlastupdated(now);
    logger.debug("update之前的操作");
  }

  @postupdate
  public void postupdate(dataentity object)
      throws illegalargumentexception, illegalaccessexception {
    logger.debug("update之后的操作");
  }

  @preremove
  public void preremove(dataentity object) {
    logger.debug("del之前的操作");

  }

  @postremove
  public void postremove(dataentity object) {
    logger.debug("del之后的操作");

  }
}

实体去实现这个对应的跟踪接口

@entitylisteners(dataentitylistener.class)
public class product implements dataentity {
     @override
  public timestamp getdatecreated() {
    return createtime;
  }

  @override
  public void setdatecreated(timestamp datecreated) {
    createtime = datecreated;
  }

  @override
  public timestamp getlastupdated() {
    return lastupdatetime;
  }

  @override
  public void setlastupdated(timestamp lastupdated) {
    this.lastupdatetime = lastupdated;
  }

  @override
  public long getdatecreatedon() {
    return createon;
  }

  @override
  public void setdatecreatedon(long datecreatedon) {
    createon = datecreatedon;
  }

  @override
  public long getlastupdatedon() {
    return lastupdateon;
  }

  @override
  public void setlastupdatedon(long lastupdatedon) {
    this.lastupdateon = lastupdatedon;
  }
}

上面代码将实现在实体保存时对createtimelastupdatetime进行赋值,当实体进行更新时对lastupdatetime进行重新赋值的操作。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网