Spring MongoRepository自定义查询

时间:2018-07-18 15:19:50

标签: spring mongodb mongorepository

嗨,我是将Spring与MongoRepository结合使用的新手,并且我正在使用Spring的MongoRepository为MongoDB创建自定义查询。 我想做的是返回对模型中另一个变量的自定义查询,而不是对象ID。

对于我的模型,我有:

@Document(collection = "useraccount")
public class UserAccounts {

    @Id
    private String id;

    private String accountNumber;
    private String firstName;
    private String lastName;

    // getters and setters
}

在我的存储库内部,我只是扩展了通用的MongoRepository:

@Repository
public interface UserAccountsRepository extends MongoRepository<UserAccounts, String> {


}

我试图创建一个自定义查询,该查询返回UserAccountsService内部的accountNumber:

@Service
public class UserAccountsService {

    private final UserAccountsRepository userAccountsRepository;

    public UserAccountsService(UserAccountsRepository userAccountsRepository) {
       this.userAccountsRepository = userAccountsRepository;
    }

    // generic find by Object id
    public UserAccounts findOne(String id) {
    Optional<UserAccounts> userAccountsOptional = 
        userAccountsRepository.findById(id);
        if(!userAccountsOptional.isPresent()) {
           throw new RuntimeException("User Account Not Found");
        }

        return userAccountsOptional.get();
    }

    // would like to implement custom query to return UserAccount if 
    // found by accountNumber variable
    public UserAccounts findOneByUserAccountNumber(String accountNumber) {

          return dormantAccountsRepository.findOne(*need query here*);;
      }
}

我将如何创建一个自定义查询以通过accountNumber而不是对象ID查找用户帐户?

任何帮助将非常感谢!

0 个答案:

没有答案