You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot中永久保存固定数据到MongoDB集合并禁止删除

实现Spring Boot启动时初始化MongoDB固定数据

1. 定义Node实体类

对应你提供的集合schema,创建Spring Data MongoDB实体类:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "Node")
public class Node {
    @Id
    private String id;
    private String value;
    private String left;
    private String right;

    // 构造方法
    public Node(String id, String value, String left, String right) {
        this.id = id;
        this.value = value;
        this.left = left;
        this.right = right;
    }

    // 省略getter、setter方法
}

2. 启动时初始化数据

通过CommandLineRunner实现启动后自动插入数据,同时避免重复插入:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
public class NodeDataInitializer implements CommandLineRunner {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void run(String... args) throws Exception {
        String targetId = "xxxx";
        // 检查目标数据是否已存在
        Node existingNode = mongoTemplate.findById(targetId, Node.class);
        if (existingNode == null) {
            // 插入固定数据
            Node fixedNode = new Node("xxxx", "1", "left_node", "right_node");
            mongoTemplate.insert(fixedNode);
        }
    }
}
禁止对Node集合执行删除操作

提供两种实现方案,按需选择:

方案1:MongoDB数据库层面限制(最安全)

通过自定义数据库角色,禁止应用用户对Node集合执行删除操作:

// 在MongoDB Shell中执行
use 你的数据库名;

// 创建自定义角色:允许读写Node集合,但禁止删除
db.createRole({
  role: "nodeCollectionSafeWriter",
  privileges: [
    { resource: { db: "你的数据库名", collection: "Node" }, actions: ["find", "insert", "update"] },
    { resource: { db: "你的数据库名", collection: "" }, actions: ["listCollections"] }
  ],
  roles: []
});

// 创建应用用户并绑定该角色
db.createUser({
  user: "spring_app_user",
  pwd: "你的密码",
  roles: [{ role: "nodeCollectionSafeWriter", db: "你的数据库名" }]
});

然后在Spring Boot配置文件中使用该用户连接:

spring.data.mongodb.uri=mongodb://spring_app_user:你的密码@localhost:27017/你的数据库名

方案2:Spring应用层面限制

方式1:自定义Repository屏蔽删除方法

不继承包含delete方法的父接口,只保留需要的操作:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface NodeRepository extends MongoRepository<Node, String> {
    // 仅定义允许的方法,如查询、保存
    Node findById(String id);
    @Override
    <S extends Node> S save(S entity);
}

方式2:AOP拦截删除操作

通过切面拦截所有针对Node集合的delete操作,直接抛出异常:

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class NodeDeleteInterceptor {

    // 拦截NodeRepository的所有delete开头方法
    @Before("execution(* 你的包路径.NodeRepository.delete*(..))")
    public void blockRepoDelete() {
        throw new UnsupportedOperationException("禁止删除Node集合数据");
    }

    // 拦截MongoTemplate针对Node集合的delete操作
    @Before("execution(* org.springframework.data.mongodb.core.MongoTemplate.delete*(..)) && args(query, collectionName)")
    public void blockTemplateDelete(Object query, String collectionName) {
        if ("Node".equals(collectionName)) {
            throw new UnsupportedOperationException("禁止删除Node集合数据");
        }
    }
}

内容的提问来源于stack exchange,提问作者leo0807

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 02:00:10