Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB auditing doesn't work for embedded documents

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?

like image 440
Egor Lyashenko Avatar asked May 19 '16 13:05

Egor Lyashenko


1 Answers

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"/>
like image 153
Egor Lyashenko Avatar answered Nov 01 '22 20:11

Egor Lyashenko