Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -16,9 +16,11 @@

package com.google.cloud.spring.data.datastore.repository.support;

import com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext;
import com.google.cloud.spring.data.datastore.core.mapping.event.BeforeSaveEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.auditing.AuditingHandler;
import org.springframework.data.mapping.PersistentEntity;

/**
* Auditing event listener that listens for {@code BeforeSaveEvent}.
Expand All @@ -29,17 +31,35 @@ public class DatastoreAuditingEventListener implements ApplicationListener<Befor

private final AuditingHandler handler;

private final DatastoreMappingContext mappingContext;

/**
* Constructor.
*
* @param datastoreAuditingHandler the auditing handler to set auditing properties.
* @param mappingContext the mapping context to check entity states.
*/
public DatastoreAuditingEventListener(AuditingHandler datastoreAuditingHandler) {
public DatastoreAuditingEventListener(
AuditingHandler datastoreAuditingHandler, DatastoreMappingContext mappingContext) {
this.handler = datastoreAuditingHandler;
this.mappingContext = mappingContext;
}

@Override
public void onApplicationEvent(BeforeSaveEvent event) {
event.getTargetEntities().forEach(this.handler::markModified);
Iterable<?> entities = event.getTargetEntities();

if (entities != null) {
entities.forEach(entity -> {
PersistentEntity<?, ?> persistentEntity =
this.mappingContext.getPersistentEntity(entity.getClass());

if (persistentEntity != null && persistentEntity.isNew(entity)) {
this.handler.markCreated(entity);
} else {
this.handler.markModified(entity);
}
});
}
}
}
}