JPA中EntityListeners注解的使用详解
使用场景
EntityListeners在jpa中使用,如果你是mybatis是不可以用的
它的意义
对实体属性变化的跟踪,它提供了保存前,保存后,更新前,更新后,删除前,删除后等状态,就像是拦截器一样,你可以在拦截方法里重写你的个性化逻辑。
它的使用
定义接口,如实体追踪
/**
*数据建立与更新.
*/
publicinterfaceDataEntity{
TimestampgetDateCreated();
voidsetDateCreated(TimestampdateCreated);
TimestampgetLastUpdated();
voidsetLastUpdated(TimestamplastUpdated);
LonggetDateCreatedOn();
voidsetDateCreatedOn(LongdateCreatedOn);
LonggetLastUpdatedOn();
voidsetLastUpdatedOn(LonglastUpdatedOn);
}
定义跟踪器
@Slf4j
@Component
@Transactional
publicclassDataEntityListener{
@PrePersist
publicvoidprePersist(DataEntityobject)
throwsIllegalArgumentException,IllegalAccessException{
Timestampnow=Timestamp.from(Instant.now());
object.setDateCreated(now);
object.setLastUpdated(now);
logger.debug("save之前的操作");
}
@PostPersist
publicvoidpostpersist(DataEntityobject)
throwsIllegalArgumentException,IllegalAccessException{
logger.debug("save之后的操作");
}
@PreUpdate
publicvoidpreUpdate(DataEntityobject)
throwsIllegalArgumentException,IllegalAccessException{
Timestampnow=Timestamp.from(Instant.now());
object.setLastUpdated(now);
logger.debug("update之前的操作");
}
@PostUpdate
publicvoidpostUpdate(DataEntityobject)
throwsIllegalArgumentException,IllegalAccessException{
logger.debug("update之后的操作");
}
@PreRemove
publicvoidpreRemove(DataEntityobject){
logger.debug("del之前的操作");
}
@PostRemove
publicvoidpostRemove(DataEntityobject){
logger.debug("del之后的操作");
}
}
实体去实现这个对应的跟踪接口
@EntityListeners(DataEntityListener.class)
publicclassProductimplementsDataEntity{
@Override
publicTimestampgetDateCreated(){
returncreateTime;
}
@Override
publicvoidsetDateCreated(TimestampdateCreated){
createTime=dateCreated;
}
@Override
publicTimestampgetLastUpdated(){
returnlastUpdateTime;
}
@Override
publicvoidsetLastUpdated(TimestamplastUpdated){
this.lastUpdateTime=lastUpdated;
}
@Override
publicLonggetDateCreatedOn(){
returncreateOn;
}
@Override
publicvoidsetDateCreatedOn(LongdateCreatedOn){
createOn=dateCreatedOn;
}
@Override
publicLonggetLastUpdatedOn(){
returnlastUpdateOn;
}
@Override
publicvoidsetLastUpdatedOn(LonglastUpdatedOn){
this.lastUpdateOn=lastUpdatedOn;
}
}
上面代码将实现在实体保存时对createTime,lastUpdateTime进行赋值,当实体进行更新时对lastUpdateTime进行重新赋值的操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。