java - MongoDB 和 Spring : How to correctly query with two fields in one repository query?

标签 java spring mongodb nosql spring-repositories

我有以下POJO:

    public class Round {

        private ObjectId _id;

        @NotEmpty
        @Getter
        @Setter
        @Accessors(fluent = true)
        @JsonProperty("userId")
        private String userId;

        // rest of fields

}

在我的 Spring boot 项目中,我尝试通过 userId 和 _id 查询我的 mongoDB,如下所示:

@Repository
public interface RoundRepository extends MongoRepository<Round, String> {

    Optional<Round> findByUserIdAnd_id(String userId, ObjectId objectId);

}

但是,当我尝试 gradlew bootRun 时,我现在得到:

Unsatisfied dependency expressed through constructor parameter 0; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'roundRepository': Invocation of init method failed; nested exception is 
org.springframework.data.mapping.PropertyReferenceException: No property and found for type String! Traversed path: Round.userId.

使用 2 个参数查询 MongoDB正确方法是什么?

最佳答案

您必须在 Round 类中使用注释@Document,并在 ID 属性中使用注释@Id:

@Document
public class Round {


        @Id
        private ObjectId _id;

        @NotEmpty
        @Getter
        @Setter
        @Accessors(fluent = true)
        @JsonProperty("userId")
        private String userId;

        // rest of fields

}

关于java - MongoDB 和 Spring : How to correctly query with two fields in one repository query?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61446650/

相关文章:

java - 使用代理参数从 Java 启动另一个 JVM

Spring Boot 测试 - 覆盖 bootstrap.properties

spring - Cordova POST - 请求禁止 403。未到达 Dispatcher Servlet

mongodb - Mongoose - 找不到结果时总是返回 null 而不是错误?

mongodb - 使用 golang bson 从 mongo 获取整个元素的问题,而不是只返回子元素

node.js - 无法通过 sails 查询整个集合(sails-mongo 或 mongodb-native)

java - 创建不包含外部依赖项的 JAR 文件

java - 使用 Repast Simphony 的意外结果

java - switch语句eclipse错误: case expressions must be constant expressions

Spring依赖注入(inject)带注释的Aspect