1

我正在像这样在 mongo 存储库中编写自定义查询:

public interface AuthenticationTokenRepository extends MongoRepository<AuthenticationToken, String> 
{

    AuthenticationToken save(AuthenticationToken token);

    AuthenticationToken findByToken(String token);

    @Query("{'user.username' : ?0}")
    AuthenticationToken findByUserId(String username);
}

但是当我试图通过 id 找出 AuthenticationToken 时,它就不起作用了。

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

我在身份验证表中的数据如下:

> db.authenticationToken.find().pretty()
{
    "_id" : ObjectId("5565b4d444ae3b1a9228be87"),
    "_class" : "com.samepinch.domain.user.AuthenticationToken",
    "token" : "545c1d10-d769-41cf-a47c-2d698ec4df72",
    "user" : {
        "_id" : ObjectId("5565b4d444ae3b1a9228be86"),
        "age" : 0,
        "username" : "dinesh.dhiman@oodlestechnologies.com",
        "firstName" : "Dinesh Dhiman",
        "email" : "dinesh.dhiman@oodlestechnologies.com",
        "gender" : "male",
        "createdDate" : ISODate("2015-05-27T12:13:08.562Z"),
        "updatedDate" : ISODate("2015-05-27T12:13:08.562Z")
    },
    "createdDate" : ISODate("2015-05-27T12:13:08.605Z"),
    "updatedDate" : ISODate("2015-05-27T12:13:26.436Z")
}

我想根据 userId 获取数据。谁能帮我。

4

2 回答 2

0

In some versions of Spring you must use ObjectId class instead of String.
So you can try something like this

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

If you want to use this query in code, it will look something like this

String userId = "someUserId";
repository.findByUserId(new ObjectId(userId));
于 2017-06-05T12:06:24.923 回答
0

我尝试了同样的例子。试试这个示例代码。它对我有用。

@Query("{user._id:?0}")
AuthenticationToken findByUser(String userId);
于 2015-12-30T12:49:39.900 回答