如何在mongodb中的集合中基于@DBRef获取记录?

时间:2015-06-01 04:43:23

标签: mongodb spring-boot

您好我正在使用mongodb与springboot并且无法在@DBRef的基础上获取记录。我的场景是:

我有AuthenticationToken Collection和User集合,如下所示:

{
    "_id" : ObjectId("556bdfc2ccf2e6509f8a2849"),
    "_class" : "com.samepinch.domain.user.AuthenticationToken",
    "token" : "2efd1cfe-2f2f-4163-b500-bac6e4654287",
    "createdDate" : ISODate("2015-06-01T04:29:54.364Z"),
    "updatedDate" : ISODate("2015-06-01T04:29:54.364Z"),
    "user" : DBRef("users", ObjectId("556bdfc2ccf2e6509f8a2848"))
}

和用户

{
    "_id" : ObjectId("556bdfc2ccf2e6509f8a2848"),
    "_class" : "com.samepinch.domain.user.User",
    "age" : 0,
    "username" : "abc@yahoo.com",
    "roles" : [
        "ROLE_USER"
    ],
    "firstName" : "abc",
    "lastName" : "mno",
    "email" : "abc@yahoo.com",
    "gender" : "male",
    "isAccountLocked" : false,
    "prefAgeFrom" : 0,
    "prefAgeTo" : 0,
    "notificationNewMatch" : true,
    "notificationMessage" : true,
    "createdDate" : ISODate("2015-06-01T04:29:54.325Z"),
    "updatedDate" : ISODate("2015-06-01T04:29:54.325Z")
}

现在我想根据身份验证集合中的用户ID获取身份验证令牌。

我使用Mongo Repository根据用户ID获取AuthenticationToken,但它无效。

获取AuthenticationToken

第1步

public AuthenticationToken findByUserId(String userId){
      ObjectId objId =  new ObjectId(userId);
        return authRepository.findByUserId(objId);
    }

第2步

public interface AuthenticationTokenRepository extends MongoRepository<AuthenticationToken, String> {

    AuthenticationToken save(AuthenticationToken token);

    AuthenticationToken findByToken(String token);

    @Query("{'user._id' : ?0}")
    AuthenticationToken findByUserId(ObjectId objId);
}

我按照上述步骤从DB获取AuthenticationToken但获取null。以前,当我在身份验证域中没有使用@DBRef用户时,它工作正常。

AuthenticationToken

public class AuthenticationToken extends BaseEntity{

    @JsonProperty
    String token;

    @DBRef
    User user;

    public AuthenticationToken(String token,User user){
        this.token = token;
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }



}

1 个答案:

答案 0 :(得分:1)

这不是什么大问题,使用像

这样的spring数据mongodb标准
Query query = new Query(Criteria.where("user.$id").is(new ObjectId(userId)));
        AuthenticationToken token = mongoTemplate.findOne(query, AuthenticationToken.class);
相关问题