“方便”和“使用功能强大”在某种程度上与目标背道而驰。到目前为止,存储库比模板方便得多,但是后者当然可以为你提供对执行内容的更细粒度的控制。
由于存储库编程模型可用于多个Spring Data模块,因此你可以在Spring Data MongoDB 参考文档的常规部分中找到有关它的更多详细文档。
TL; DR
我们通常建议采用以下方法:
从存储库摘要开始,仅使用查询派生机制或手动定义的查询声明简单查询。
对于更复杂的查询,将手动实现的方法添加到存储库中(如此处所述)。供实现使用MongoTemplate。
细节
对于你的示例,这看起来像这样:
- 为你的自定义代码定义一个接口:
interface CustomUserRepository { List<User> yourCustomMethod();}- 为该类添加一个实现,并遵循命名约定以确保我们可以找到该类。
class UserRepositoryImpl implements CustomUserRepository { private final MongoOperations operations; @Autowired public UserRepositoryImpl(MongoOperations operations) { Assert.notNull(operations, "MongoOperations must not be null!"); this.operations = operations; } public List<User> yourCustomMethod() { // custom implementation here }}- 现在,让你的基本存储库界面扩展自定义界面,基础结构将自动使用你的自定义实现:
interface UserRepository extends CrudRepository<User, Long>, CustomUserRepository {}


