把 JSON 文档转换成 Spring Data MongoDB 的 @Document 类:在 @Document 中指定集合名,带一个 @Id 字段,每个 key 对应一个 private 字段(存储的 key 不同时加 @Field),再加上 Lombok 和 jakarta.validation 注解,全部放在一个 Java 文件中。
当以普通 JSON 形式落进 MongoDB 的数据(IoT 读数、事件、抓取结果)需要在 Spring Boot 服务中通过 MongoRepository 读写时,就可以用它。
mongosh 中 find().limit(5) 的输出),能区分出偶尔出现的字段和始终存在的字段。模型名(留空则为 MyModel);它同时用作类名和 @Document(collection = "...") 中的集合名。package 行,保存文件,再创建一个继承 MongoRepository<DeviceLog, String> 的 repository。[
{ "device_id": "th-sensor-07", "temperature": 21.4, "battery": 87, "online": true, "recorded_at": "2024-02-11T06:00:00Z" },
{ "device_id": "th-sensor-09", "temperature": 19.8, "battery": 12, "online": false, "recorded_at": "2024-02-11T06:00:00Z", "firmware": "1.4.2" }
]package com.hello.world.devicelog;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.FieldNameConstants;
@Document(collection = "DeviceLog")
@FieldNameConstants
@Getter
@Setter
public class DeviceLog {
@Id
private String id;
@NotEmpty()
@Field("device_id")
private String deviceId;
@NotNull()
private Double temperature;
@NotNull()
private Long battery;
@NotNull()
private Boolean online;
@NotNull()
@Field("recorded_at")
private LocalDateTime recordedAt;
private String firmware;
}firmware 只出现在第二个文档中,所以没有注解。device_id 和 recorded_at 通过 @Field("device_id") 和 @Field("recorded_at") 读取,现有文档无需迁移就能映射到 camelCase 字段。
@Document(collection = "DeviceLog") 显式指定集合名。@Id private String id 存放 MongoDB 的 _id;JSON 中的 id 或 _id key 会合并到这里而不会重复,数值型 id 会让它变成 Long。Long、Double、Boolean、LocalDate(YYYY-MM-DD)、LocalDateTime(日期时间)或 String;嵌入对象变成 Map<String, Object>,数组变成 List<...>。@Field("..."),包括加了后缀 _ 的 Java 关键字。@NotEmpty(),其他得到 @NotNull();偶尔出现或为 null 的字段不加注解。设备直接写入 MongoDB 的读数需要提供给仪表盘时,粘贴几个文档得到类,就能立刻声明 findByDeviceIdOrderByRecordedAtDesc 这样的派生查询。
如果 Spring 需要读取另一个服务已经用 snake_case 写入的集合,@Field 注解能让 Java 一侧使用 camelCase 名称,同时读写相同的 key。
@NotEmpty 和 @NotNull;注册一个 ValidatingMongoEventListener bean,就能在 save() 之前进行校验。LocalDateTime 在 MongoDB 中存为基于 UTC 的 Date,根据服务器时区不同,读出时可能出现偏移。对精确时刻很重要的日志,用 Instant 更安全。Long 类型的 id 不会由 MongoDB 生成,必须在保存前自行赋值。只有 String、ObjectId 和 BigInteger 类型的 id 会被自动填充。Map<String, Object>。需要类型化访问和校验时,请替换成小的类。_id,为什么字段叫 id?Spring Data 会自动把名为 id(或带 @Id 注解)的字段映射到 _id,当 String 看起来像 ObjectId 时还会自动转换。不需要自己声明 _id。
device_logs。直接修改字符串即可:@Document(collection = "device_logs")。生成器会把模型名原样填入,所以如果把模型名输入成 device_logs,类名也会变成 DeviceLogs。
它使用 @Document、@Field 和 Spring Data 的 @Id,而不是 @Entity、@Column 和 @GeneratedValue;嵌套的值直接嵌入,不需要 JSON 列。关系型表请使用 JSON → Spring Boot JPA 页面。