For further explanation, you can even use both at the same time.
MongoRepository is just an abstraction layer like MongoTemplate , but with a simpler interface.
If you find that performing an operation is too complicated in Spring- creating queries and for some reason does not want to use @Query (for example, you need a hint like IDE when building queries), you can extend MongoRepository and use MongoTemplate as a query mechanism.
First, we expand our repository using our user 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 own repository. We can automatically connect 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); } }
Finally, we use ArticleRepository .
@Service public class ArticleServiceImpl { @Autowired private ArticleRepository articleRepository; public List<Article> getArticleByPage() { return articleRepository.getArticleFilteredByPage(1, 10); } }
Adhika setya pramudita
source share