这篇文章主要介绍了JPA中EntityListeners注解的使用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
使用场景
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 进行重新赋值的操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持CodeAE代码之家。
原文链接:http://www.cnblogs.com/lori/p/10243256.html
|