内容简介:EntityListeners在jpa中使用,如果你是mybatis是不可以用的对实体属性变化的跟踪,它提供了保存前,保存后,更新前,更新后,删除前,删除后等状态,就像是拦截器一样,你可以在拦截方法里重写你的个性化逻辑。上面代码将实现在实体保存时对
使用场景
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
进行重新赋值的操作。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- java注解使用总结
- Retrofit使用详解-注解介绍
- SpringMVC入门学习---使用注解开发
- 结合案例使用 Java 注解和反射
- Java之注解的定义及使用
- Spring管理的@Configuration注解使用
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Rework
Jason Fried、David Heinemeier Hansson / Crown Business / 2010-3-9 / USD 22.00
"Jason Fried and David Hansson follow their own advice in REWORK, laying bare the surprising philosophies at the core of 37signals' success and inspiring us to put them into practice. There's no jarg......一起来看看 《Rework》 这本书的介绍吧!