带有 MongoTemplate 的 Spring Boot [英] Spring Boot with MongoTemplate
问题描述
我是 Spring Boot 和 MongoDb 的新手.使用 Mongo Repositories 和 Spring Boot 尝试一些示例.但是在查阅了一些文档后发现 Mongo Template 会是一个更好的选择.无法使用 Mongo 模板示例获得正确的 Spring Boot.
I am new to Spring Boot and MongoDb. Trying some examples with Mongo Repositories and Spring Boot. But after going through some of the documents found that Mongo Template is will be a better option. Unable to get a proper Spring Boot with Mongo Template example.
谁能帮我举个例子.
Can someone please help me out with an example for the same.
在尝试 Mongo 模板时,我们是否需要创建用户定义的 Repositories 接口并扩展 Repositories 或 CRUD Repository?
Do we need to create a User defined Repositories interface and extend Repositories or CRUD Repository, while trying for Mongo Template ?
推荐答案
为了进一步说明,您甚至可以同时使用两者.
For further explanation, you can even use both at the same time.
MongoRepository
只是一个抽象层,就像 MongoTemplate
一样,但接口更简单.
MongoRepository
is just an abstraction layer, like MongoTemplate
, but with simpler interface.
如果你发现用 Spring 做某种操作太复杂了 query-creation,不知何故不想使用 @Query
(例如,您在构造查询时需要 IDE 类型提示),可以扩展MongoRepository
,使用MongoTemplate
作为查询机制.
If you found doing some kind of operation is too complicated with Spring query-creation, and somehow doesn't want to use @Query
(for example, you want IDE type hint when constructing queries), you can extend the MongoRepository
and use MongoTemplate
as the query mechanism.
首先,我们使用自定义界面扩展我们的存储库.
First we extend our repository with our custom interface.
@Repository
public interface ArticleRepository extends MongoRepository<Article, String>, CustomArticleRepository {
}
然后声明接口.
public interface CustomArticleRepository {
List<Article> getArticleFilteredByPage(int page, int num);
}
然后实现我们的自定义存储库.我们可以在这里自动装配 MongoTemplate
并使用它来查询数据库.
And then implement our custom repository. We can autowire the MongoTemplate
here and use it to query the database.
public class CustomArticleRepositoryImpl implements CustomArticleRepository {
@Autowired
MongoTemplate mongoTemplate;
@Override
public List<Article> getArticleFilteredByPage(int page, int num) {
return mongoTemplate.findAll(Article.class)
.skip(page * num)
.take(num);
}
}
最后,我们使用ArticleRepository
.
@Service
public class ArticleServiceImpl {
@Autowired
private ArticleRepository articleRepository;
public List<Article> getArticleByPage() {
return articleRepository.getArticleFilteredByPage(1, 10);
}
}
这篇关于带有 MongoTemplate 的 Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!