使用场景
entitylisteners在jpa中使用,如果你是mybatis是不可以用的
它的意义
对实体属性变化的跟踪,它提供了保存前,保存后,更新前,更新后,删除前,删除后等状态,就像是拦截器一样,你可以在拦截方法里重写你的个性化逻辑。
它的使用
定义接口,如实体追踪
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/**
* 数据建立与更新.
*/
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);
}
|
定义跟踪器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
@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之后的操作" );
}
}
|
实体去实现这个对应的跟踪接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
@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 进行重新赋值的操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/lori/p/10243256.html