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; } }
上面代码将实现在实体保存时对 createTime
, lastUpdateTime
进行赋值,当实体进行更新时对 lastUpdateTime
进行重新赋值的操作。