Spring-data mongodb repository and inheritance

2019-07-15 18:58发布

I have created a class user class like that :

public class User {
    /**
     * The list of roles for the user
     */
    private List<String> roles;
    /**
     * The login information
     */
    private ICredentials credentials;

    /*---- the constructors and getters/setters are omitted ---*/
}

The ICredentials interface :

public interface ICredentials {
}

One implementation :

public class LoginPassword implements ICredentials {
    /**
     * The login of the user
     */
    protected String login;

    /**
     * The password of the user
     */
    protected String password;

    /*---- the constructors and getters/setters are omitted ---*/
}

Now, I have created a repository to find a user from credentials :

public interface MongoUserRepository extends MongoRepository<User, String> {
    List<User> findByCredentials(ICredentials credentials);
    List<User> findByCredentialsEquals(ICredentials credentials);
}

Spring logs this (for both requests) : org.springframework.data.mongodb.core.MongoTemplate [DEBUG] find using query: { "credentials" : { "login" : "test" , "password" : "test"}} fields: null for class: class xxx.User in collection: user

And it doesn't found anything... It seems that it doesn't found anything because the "_class" attribute is not written is the request. I think the good request should be: { "credentials" : {"_class":"xxx.LoginPassword", "login" : "test" , "password" : "test"}}

Is something I doing wrong ? Am I missing something ?

Thanks

I use spring mvc 3.2.0, spring-data-commons-core 1.4.0, spring-data-mongodb 1.1.1 and mongo-java-driver 2.10.1 (I have updated all libraries to the latest version to be sure it wasn't a bug already fixed but no success)

2条回答
Bombasti
2楼-- · 2019-07-15 19:44

It occurs when you not using annotations for your document

@Document(collection = "example")
public class Example{

  @Id
  private String id;

  //getter and setters
}
查看更多
小情绪 Triste *
3楼-- · 2019-07-15 19:47

Did you try to add @Document(collection = "users") above your ICredentials interface ?

查看更多
登录 后发表回答