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.
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
is just an abstraction layer, like MongoTemplate
, but with simpler interface.
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 {
}
Then declare the interface.
public interface CustomArticleRepository {
List<Article> getArticleFilteredByPage(int page, int num);
}
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);
}
}
Last, we use the ArticleRepository
.
@Service
public class ArticleServiceImpl {
@Autowired
private ArticleRepository articleRepository;
public List<Article> getArticleByPage() {
return articleRepository.getArticleFilteredByPage(1, 10);
}
}