@JsonProperty 注释在 mongodb 集合中被忽略

@JsonProperty annotation is getting ignored in mongodb collection

由于我是 springbootmongodb 的新手,所以我使用了 https://start.spring.io/ 并使用以下设置生成了一个演示项目。

然后创建如下模型:

package com.example.model;

import java.io.Serializable;
import java.time.LocalDate;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Document;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@Configuration

@Document(collection = "customer")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer implements Serializable {
    
    private static final long serialVersionUID = 6748432793461621268L;

    @JsonProperty("customer_id")
    private String customerId;
    
    @JsonProperty(value= "external_customer_reference_id")
    private String externalCustomerReferenceId;
    
    
    @JsonProperty("title")
    private String title;

    @JsonProperty("first_name")
    private String firstName;
    
    @JsonProperty("middle_name")
    private String middleName;

    @JsonProperty("last_name")
    private String lastName;
    
    @JsonProperty("email")
    private String email;

    @JsonProperty("phone")
    private String phone;

    @JsonProperty("note")
    private String note;
    
    @JsonProperty("date_of_birth")
    private String dateOfBirth;

    @JsonProperty("sex")
    private String sex;
    
    @JsonProperty("contact_address")
    private Address address;
    
    @CreatedDate
    @JsonProperty("create_timestamp")
    private LocalDate createdDate;
    
    @LastModifiedDate
    @JsonProperty("modified_timestamp")
    private LocalDate modifiedDate;
    
    
}

我能够在 mongodb 集合 customer 中保存客户。但集合属性名称与 @JsonProperty("modified_timestamp").

不同

为什么数据库集合属性名称与JsonProperty不一样?如何获得与 JsonProperty 相同的数据库集合属性名称?

在 MongoDB 中,您正在保存一个对象及其属性名称。 JsonProperty 注释映射给定对象的反序列化和序列化。

Marker annotation that can be used to define a non-static method as a "setter" or "getter" for a logical property (depending on its signature), or non-static object field to be used (serialized, deserialized) as a logical property. Default value ("") indicates that the field name is used as the property name without any modifications, but it can be specified to non-empty value to specify different name. Property name refers to name used externally, as the field name in JSON objects.

https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonProperty.html

通过使用 @Field 属性 注释,您可以将 属性 保存为与对象不同的名称。