当前位置: 首页 > article >正文

SpringBoot如何在使用MongoRepository时启用@Created

欢迎转载,但请标明出处和引用本文地址

1. 需要的依赖

对于 MongoDB,首先要确保你引入了以下依赖:Spring Boot Starter Data MongoDB

这是用于支持 MongoDB 的基础依赖,替代 spring-boot-starter-data-jpa

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2. 启用 MongoDB 审计功能

与 JPA 类似,MongoDB 审计也需要启用。首先,在主类上启用 MongoDB 的审计功能。

在主类上添加 @EnableMongoAuditing

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.config.EnableMongoAuditing;

@SpringBootApplication
@EnableMongoAuditing // 重要
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3. 实体类上添加审计注解

与 JPA 类似,在 MongoDB 的实体类(通常是文档类)中添加 @CreatedBy@CreatedDate 注解。

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Document;

import java.time.LocalDateTime;

@Document  // 指定 MongoDB 中的集合名称
public class MyDocument {

    @Id
    private String id;

    @CreatedBy
    private String createBy;

    @CreatedDate
    private LocalDateTime createdDate;

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    private LocalDateTime lastModifiedDate;

    // getter 和 setter
}

4. 配置 AuditorAware Bean

MongoDB 审计同样需要一个 AuditorAware 实现,用来提供当前用户信息。以下是基于 Spring Security 的实现:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Optional;

@Configuration
public class AuditConfig {

    @Bean
    public AuditorAware<String> auditorProvider() {
        return new AuditorAwareImpl();
    }

    public static class AuditorAwareImpl implements AuditorAware<String> {

        @Override
        public Optional<String> getCurrentAuditor() {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return Optional.empty();
            }
            return Optional.of(((UserDetails)authentication.getPrincipal()).getUsername()); // 返回当前用户名
        }
    }
}

5. 配置 MongoDB 连接

还需要在 application.properties(或 application.yml)文件中配置 MongoDB 连接。

5. 检查配置(重要)

如果你创建实体类时,例如上文所提到的MyDocument实体类时进行了如下操作

MyDocument myDocument = new MyDocument();
// 主动的添加id
myDocument.setId(ObjectId.get().toString());
// ... 其它的赋值操作

// 存储数据库
MyDocumentMongoRepository.save(myDocument);


// 样例代码,在csdn中编辑,有错误请指出

MongoRepository的相关代码进行添加审计注解时,会判断你这个类是不是新创建的类,如果时新创建的类,会执行注入

@CreatedBy @LastModifiedBy @CreatedDate @LastModifiedDate

标注的的参数,如果不是新创建的类则只会注入

@LastModifiedBy @LastModifiedDate

这两个更新标识的参数,

相关代码判断是否是新创建的类的条件是:判断@Id所标识的字段是否为 NULL(或者你没有使用@Id标识,但是有一个String或者ObjectId类型的id字段,会默认是id)

以上是实践所得出,如有出入可能是springboot版本不一致导致,请根据自己实际情况测试

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.8</version>
        <relativePath/>
    </parent>


http://www.kler.cn/news/314186.html

相关文章:

  • [Python数据拟合与可视化]:使用线性、多项式、指数和高斯模型拟合数据
  • 【Stm32】从零建立一个工程
  • Science Robotic 内在触觉实现直观的物理人机交互
  • Docker 进阶篇-CIG 重量级监控系统
  • 4 + 1 视图模型
  • vue MVC设计模式与MVVM设计模式
  • ByteTrack多目标跟踪流程图
  • 一次RPC调用过程是怎么样的?
  • 12- 【JavaWeb】校园快递管理系统-数据库建设
  • JS中判断字符串中是否包含指定字符
  • 百易云资产管理运营系统 ticket.edit.php SQL注入漏洞复现
  • c++应用网络编程之九Linux下的select模式
  • python安装-升级
  • Python数据分析与可视化实战指南
  • 网安面试会问到的:http的长连接和短连接
  • Kafka消息堆积问题排查
  • Pikachu靶场之csrf
  • CompletableFuture的allOf一定不要乱用!血泪史复盘
  • 重修设计模式-结构型-组合模式
  • 网络丢包定位记录(三)
  • 海外大带宽服务器连接失败怎么办?
  • Antd框架中的Select组件placeholder不显示
  • [苍穹外卖]-11数据可视化接口开发
  • Qt 窗口事件机制
  • 分页查询,pageHelper, pagehelper-spring-boot-starter
  • C++ 策略技术中的算法策略
  • 握手传输 状态机序列检测(记忆科技笔试题)_2024年9月2日
  • 构建高可用和高防御力的云服务架构第一部分:深入解析DDoS高防(1/5)
  • 财富之眼用经济思维看清世界PDF高清下载
  • 【FastAPI】服务器使用SSE实现客户端之间的广播和点对点功能