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

Spring Boot中Java类映射MongoDB集合及对应注解相关问题

Spring Boot 对接MongoDB Java类映射方案

1 对应JPA @Entity的替代注解

spring-boot-starter-data-mongodb 中提供了和JPA @Entity功能完全对等的映射注解:@org.springframework.data.mongodb.core.mapping.Document,加在Java类上即可标识该类为MongoDB集合的映射实体类。

2 完整映射实现步骤

  • 第一步:引入MongoDB Starter依赖
    在pom.xml中添加如下依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  • 第二步:编写实体类添加映射注解
    示例代码如下:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.annotation.Transient;

// 可选通过collection参数指定映射的集合名,不填默认用类名首字母小写作为集合名
@Document(collection = "user_info")
public class User {
    // 对应MongoDB文档的_id主键字段,必须标注@Id
    @Id
    private String userId;
    
    // 可选通过@Field自定义映射的MongoDB字段名,不填默认和Java属性名一致
    @Field("user_age")
    private Integer age;
    
    private String userName;
    
    // 标注@Transient的属性不会被持久化到MongoDB
    @Transient
    private String tempBusinessField;

    // 省略构造方法、getter、setter
}
  • 第三步:编写Repository层操作集合
    继承MongoRepository即可直接使用封装好的CRUD能力,无需手动编写实现:
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;

public interface UserRepository extends MongoRepository<User, String> {
    // 可按Spring Data规则自定义查询方法
    List<User> findByAgeGreaterThan(Integer minAge);
}

3 常用映射注解说明

  • @Id:标记主键字段,对应MongoDB文档的_id字段,支持String、ObjectId、Long类型,插入时主键为空会由MongoDB自动生成主键值
  • @Field:自定义Java属性与MongoDB字段的映射关系
  • @Transient:标记临时属性,不会持久化到数据库
  • @Indexed:为对应字段添加索引,提升查询性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 14:24:03