代码之家  ›  专栏  ›  技术社区  ›  luca

当我使用@JsonProperty通过Spring数据从MongoDB检索对象时,为空字段

  •  0
  • luca  · 技术社区  · 6 年前

    我在使用Spring JPA、MongoDB和Jackson时遇到了一些问题 @JsonProperty 为json/db和java字段使用不同的名称。 我接收json并将其保存到集合中,例如

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @Document(collection="message")
    public class Message implements java.io.Serializable{
    
        private static final long serialVersionUID = 1L;
    
        @Id
        private String id;
    
        @JsonProperty("raw")
        private Raw raw;
    
        @JsonProperty("meta")
        private Meta meta;      
    }
    

    带原材料:

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @Document(collection="raw")
    public class Raw {
    
        private String dlc;
    
        @JsonProperty("can_id")
        private String canId;
    
        @JsonProperty("can_data")
        private String canData;
    }
    

    我在使用lombok作为get、set和构造函数。我得到了 message 在更改字段名之前进入数据库(例如使用 canData can_data )当我从数据库中检索对象时,这个重命名的字段为空。所以我删除了消息并再次存储,最后工作了,我之所以这样做是因为在mongodb中我看到 _class:"com.domain.Message" .

    但是,即使在Mongodb中手动插入json,我也有问题:我使用的字段 @JsonProperty公司 当我进行如下查询时为空:

    @Query("{ 'can_id' : ?0 }")
    Severity findByCanId(String canId);
    

    Severity 是这样的:

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @Document(collection="severity")
    public class Severity implements java.io.Serializable{
    
        private static final long serialVersionUID = 1L;
    
        @JsonProperty("can_id")
        @Indexed
        private String canId;       
    
        @JsonProperty("can_name")
        private String canName;
    
        private Integer ss;
    
        private Integer ps;
    
        private Integer fs;
    
        private Integer os;
    }
    

    严重程度 canId canName 无效的。 你知道我该怎么解决这个问题吗?谢谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   luca    6 年前

    对于数据库中字段的名称,我使用 @Field("can_id") 但是java类stil的变化问题