19
19
import org .springframework .context .ApplicationListener ;
20
20
import org .springframework .data .auditing .AuditingHandler ;
21
21
import org .springframework .data .jdbc .mapping .event .BeforeSaveEvent ;
22
+ import org .springframework .data .jdbc .mapping .model .JdbcMappingContext ;
23
+ import org .springframework .data .jdbc .mapping .model .JdbcPersistentEntityInformation ;
22
24
import org .springframework .data .jdbc .repository .config .EnableJdbcAuditing ;
23
25
import org .springframework .lang .Nullable ;
24
26
import org .springframework .util .Assert ;
35
37
public class JdbcAuditingEventListener implements ApplicationListener <BeforeSaveEvent > {
36
38
37
39
@ Nullable private AuditingHandler handler ;
40
+ private JdbcMappingContext context ;
38
41
39
42
/**
40
43
* Configures the {@link AuditingHandler} to be used to set the current auditor on the domain types touched.
@@ -48,6 +51,17 @@ public void setAuditingHandler(ObjectFactory<AuditingHandler> auditingHandler) {
48
51
this .handler = auditingHandler .getObject ();
49
52
}
50
53
54
+ /**
55
+ * Configures a {@link JdbcMappingContext} that use for judging whether new object or not.
56
+ * @param context must not be {@literal null}
57
+ */
58
+ public void setJdbcMappingContext (JdbcMappingContext context ) {
59
+
60
+ Assert .notNull (context , "JdbcMappingContext must not be null!" );
61
+
62
+ this .context = context ;
63
+ }
64
+
51
65
/**
52
66
* {@inheritDoc}
53
67
*
@@ -59,11 +73,14 @@ public void onApplicationEvent(BeforeSaveEvent event) {
59
73
if (handler != null ) {
60
74
61
75
event .getOptionalEntity ().ifPresent (entity -> {
62
-
63
- if (event .getId ().getOptionalValue ().isPresent ()) {
64
- handler .markModified (entity );
65
- } else {
76
+ @ SuppressWarnings ("unchecked" )
77
+ Class <Object > entityType = event .getChange ().getEntityType ();
78
+ JdbcPersistentEntityInformation <Object , ?> entityInformation =
79
+ context .getRequiredPersistentEntityInformation (entityType );
80
+ if (entityInformation .isNew (entity )) {
66
81
handler .markCreated (entity );
82
+ } else {
83
+ handler .markModified (entity );
67
84
}
68
85
});
69
86
}
0 commit comments