EntityListeners注解怎么在JPA中使用

EntityListeners注解怎么在JPA中使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

使用场景

EntityListeners注解怎么在JPA中使用

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;
}
}

看完上述内容,你们掌握EntityListeners注解怎么在JPA中使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注恰卡编程网行业资讯频道,感谢各位的阅读!

发布于 2021-03-26 01:49:24
收藏
分享
海报
0 条评论
177
上一篇:如何在易语言中使用拖放组件 下一篇:怎么在Spring boot中使用Junit进行单体测试
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码