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中使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注恰卡编程网行业资讯频道,感谢各位的阅读!
推荐阅读
-
springboot jpa延迟加载问题怎么解决
springbootjpa延迟加载问题怎么解决本文小编为大家详细...
-
Springboot使用Spring(Data,JPA实现数据库操作)
Springboot使用Spring,Data,JPA实现数据库操作,恰卡网带你了解更多相关信息。SpringBoot整合...
-
使用jpa原生[email protected]操作增删改查
jpa原生[email protected]操作增删改查1、jpa原生update的sql语句:1.命名参数(推荐...
-
Spring,Data,JPA中,in,条件参数的传递方式
关于SpringDataJPA中自定义sql条件的in参数记录此文做一个记录,以便以后观看,也希望正在遇到同样问题的同学...
-
解决springboot的JPA在Mysql8新增记录失败的问题
springboot的JPA在Mysql8新增记录失败springboot版本是1.3.0.M1,连接的mysql版本为8,用s...