Spring Data MongoDB审核不适用于嵌入式文档

Ego*_*nko 5 java spring mongodb spring-data-mongodb

我试图通过使用Spring Data MongoDB @LastModifiedDate注释来引入审计。它适用于顶级文档,但我遇到了嵌入式对象的问题。

例如:

@Document(collection = "parent")
class ParentDocument {

    @Id
    String id;        

    @LastModifiedDate
    DateTime updated;

    List<ChildDocument> children;  

}

@Document
class ChildDocument {

    @Id
    String id;        

    @LastModifiedDate
    DateTime updated;

}
Run Code Online (Sandbox Code Playgroud)

默认情况下,当我parentDocument使用内部children列表保存实例时,updated仅为列表中的parentDocument任何对象设置值,而不为该对象设置值children。但是在这种情况下,我也想对其进行审核。是否可以通过某种方式解决此问题?

Ego*_*nko 1

我决定使用自定义来解决它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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将相应的bean添加到应用程序上下文中

<bean id="customAuditingEventListener" class="app.CustomAuditingEventListener"/>
Run Code Online (Sandbox Code Playgroud)