返回
MongoDB 审计:轻松搞定公共字段维护!
后端
2023-10-04 04:10:13
数据库中的公共字段,如创建人、更新人、创建时间、更新时间等,在使用 MongoDB 时如何统一维护呢?别担心,我来教你一招搞定!
缘起
最近在公司使用 MongoDB 这种文档数据库,和 MySQL 一样在设计表实体时候都有一些公有的字段,比如,创建人、更新人、创建时间、更新时间。那么 MongoDB 如何统一维护这些字段呢?
MongoDB 审计
MongoDB 提供了 Auditing 功能,可以自动维护这些公共字段。下面我将介绍如何使用 SpringDataMongodb 实现 MongoDB 审计。
步骤
- 配置 Auditing 功能
在 Spring Boot 项目中,需要在 application.properties 文件中配置 Auditing 功能。
spring.data.mongodb.auditing.enabled=true
- 使用注解
在实体类中,可以使用 @CreatedBy、@LastModifiedBy、@CreatedDate、@LastModifiedDate 注解来标记公共字段。
@Entity
public class Person {
@Id
private String id;
private String name;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String lastModifiedBy;
@CreatedDate
private Date createdDate;
@LastModifiedDate
private Date lastModifiedDate;
// getter and setter methods
}
- 编写监听器
需要编写一个监听器来记录审计信息。
public class AuditingEntityListener implements ApplicationContextAware {
private UserContextHolder userContextHolder;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.userContextHolder = applicationContext.getBean(UserContextHolder.class);
}
@EventListener
public void onPrePersist(BeforeSaveEvent<Object> event) {
Object entity = event.getEntity();
if (entity instanceof Auditable) {
Auditable auditable = (Auditable) entity;
auditable.setCreatedBy(userContextHolder.getCurrentUsername());
auditable.setCreatedDate(new Date());
}
}
@EventListener
public void onPreUpdate(BeforeUpdateEvent<Object> event) {
Object entity = event.getEntity();
if (entity instanceof Auditable) {
Auditable auditable = (Auditable) entity;
auditable.setLastModifiedBy(userContextHolder.getCurrentUsername());
auditable.setLastModifiedDate(new Date());
}
}
}
总结
通过以上步骤,即可轻松实现 MongoDB 公共字段的自动维护。