1.增删改
@Test public void testSave() { Article article = new Article(); article.setId(2); article.setTitle("java高级-存在与虚无"); article.setContent("头发还好吗?"); article.setHits(10000); articleDao.save(article); } @Test public void testDelete() { articleDao.deleteById(1); } @Test public void testUpdate() { Article article = new Article(); article.setId(2); // id存在则更新 article.setTitle("java高级-存在与虚无"); article.setContent("头发还好吗?头发还好吗?头发还好吗?头发还好吗?头发还好吗?"); article.setHits(10001); articleDao.save(article); }
2.简单查询
@Test public void testFindAll() { List<Article> list = articleDao.findAll(); for (Article article : list) { System.out.println(article); } } @Test public void testFindById() { Optional<Article> opt = articleDao.findById(1); System.out.println(opt.get()); } @Test public void testFindWithPage() { Page<Article> page = articleDao.findAll(PageRequest.of(0, 3)); System.out.println("总页数:" + page.getTotalPages()); System.out.println("总记录数:" + page.getTotalElements()); System.out.println("当前页:" + page.getNumber()); for (Article article : page.getContent()) { System.out.println(article); } } @Test public void testFindWithSort() { Iterable<Article> iterable = articleDao.findAll(Sort.by(Sort.Order.desc("id"))); for (Article article : iterable) { System.out.println(article); } } @Test public void testFindWithPageAndSort() { PageRequest page = PageRequest.of(1, 10, Sort.by(Sort.Order.desc("hits"))); Page<Article> all = articleDao.findAll(page); System.out.println("总页数:" + all.getTotalPages()); System.out.println("总记录数:" + all.getTotalElements()); System.out.println("当前页:" + all.getNumber()); for (Article article : all.getContent()) { System.out.println(article); } }
3.命名规则查询
命名规则跟jpa基本一致,常见的如下:
定义接口:
public interface ArticleDao extends MongoRepository<Article, Integer> { // 根据标题模糊查询 List<Article> findByTitleLike(String title); //根据点击量大于?查询 List<Article> findByHitsGreaterThan(Integer hits); }
测试:
@Test public void testFindByTitleLike() { List<Article> list = articleDao.findByTitleLike("java1"); for (Article article : list) { System.out.println(article); } } @Test public void testFindByHitsGreaterThan() { List<Article> list = articleDao.findByHitsGreaterThan(200); for (Article article : list) { System.out.println(article); } }