【问题标题】:Spring MongoDB find sets annotated id field as nullSpring MongoDB find 将带注释的 id 字段设置为 null
【发布时间】:2021-12-30 02:20:57
【问题描述】:

我正在使用 spring-data-mongodb 将我的 Java 对象保存到 MongoDB。除一项特定操作外,一切正常:

 @Override
 public Collection<MyDocument> findAllByTags(Collection<String> tags) {
        FindIterable<MyDocument> results = operations.getCollection(COLLECTION_NAME)
                .find(Filters.all(FIELD_TAGS, tags), MyDocument.class);
        return StreamSupport.stream(results.spliterator(), false).collect(Collectors.toList());
 }

文档类如下所示:

@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Document
public class MyDocument implements MyEntity {


    @Id
    @EqualsAndHashCode.Include
    @BsonProperty("myId")
    private String myId;

    @BsonProperty("dateCreated")
    private Date dateCreated;

    @BsonProperty("otherField")
    private String otherField;

    @Indexed
    @BsonProperty("tags")
    private Collection<String> tags;

    //more fields

所有对象的所有字段都按预期返回,但带有@Id 注释的字段设置为null。有谁知道是什么导致了这种行为以及如何解决它?感谢您的宝贵时间。

【问题讨论】:

    标签: java spring mongodb


    【解决方案1】:

    我得到它的工作如下:

     @Getter
     @Setter
     @NoArgsConstructor
     @EqualsAndHashCode(onlyExplicitlyIncluded = true)
     @Document
     public class MyDocument implements MyEntity {
        
        
        @MongoId(value = FieldType.STRING)
        private String myId;
    
       //... 
    

    还有查询:

     @Override
     public Collection<MyDocument> findAllByTags(Collection<String> tags) {
         return operations.find(query(Criteria.where(FIELD_TAGS).all(tags)), MyDocument.class);
     }
    

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2019-06-15
      • 1970-01-01
      • 2018-04-13
      • 2018-04-25
      相关资源
      最近更新 更多