Write custom query in mongodb repository

我只是一个虾纸丫 提交于 2020-01-05 13:08:12

问题


I am writing custom query in mongo repository like this :

public interface AuthenticationTokenRepository extends MongoRepository<AuthenticationToken, String> 
{

    AuthenticationToken save(AuthenticationToken token);

    AuthenticationToken findByToken(String token);

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

But when i tried to findout AuthenticationToken by id then it is not working.

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

My data in authentication table is as following:

> 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")
}

I want to fetch data on the basis of userId. Can anyone help me.


回答1:


I tried the same example. Try this sample code. It worked for me.

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



回答2:


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));


来源:https://stackoverflow.com/questions/30482482/write-custom-query-in-mongodb-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!