I'm trying to introduce auditing by using Spring Data MongoDB @LastModifiedDate
annotation. It works fine for top-level documents but I've faced with the problem for embedded objects.
For example:
@Document(collection = "parent")
class ParentDocument {
@Id
String id;
@LastModifiedDate
DateTime updated;
List<ChildDocument> children;
}
@Document
class ChildDocument {
@Id
String id;
@LastModifiedDate
DateTime updated;
}
By default, when I save parentDocument
instance with inner children
list, updated
value is set only for parentDocument
but not for any object from the children
list. But in this case I want to audit them too. Is it possible to solve this problem somehow?
I've decided to solve it using custom ApplicationListener
public class CustomAuditingEventListener implements
ApplicationListener<BeforeConvertEvent<Object>> {
@Override
public void onApplicationEvent(BeforeConvertEvent<Object> event) {
Object source = event.getSource();
if (source instanceof ParentDocument) {
DateTime currentTime = DateTime.now();
ParentDocument parent = (ParentDocument) source;
parent.getChildren().forEach(item -> item.setUpdated(currentTime));
}
}
}
And then add corresponding bean to the application context
<bean id="customAuditingEventListener" class="app.CustomAuditingEventListener"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With