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 进行重新赋值的操作。

以上是 JPA中EntityListeners注解的使用详解 的全部内容, 来源链接: utcz.com/z/312834.html

回到顶部