Spring Data MongoDB auditing doesn't work for embedded documents

牧云@^-^@ 提交于 2020-07-18 10:55:31

问题


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?


回答1:


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"/>


来源:https://stackoverflow.com/questions/37324188/spring-data-mongodb-auditing-doesnt-work-for-embedded-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!