1. 建立Blog存储库,继承 ElasticsearchRepository 类,重写 findByTitleLikeOrContentLike 方法。
public interface BlogRepository extends ElasticsearchRepository<Blog, String> {
/**
* 分页查询博客
* @param title
* @param content
* @param pageable
* @return
*/
Page<Blog> findByTitleLikeOrContentLike(String title, String content, Pageable pageable);
}
2. 测试类,存储数据到blogRepository,
@RunWith(SpringRunner.class)
@SpringBootTest
public class BlogRepositoryTest {
@Autowired
private BlogRepository blogRepository;
@Test
public void testFindByTitleLikeOrFindContentLike() {
// 清空所有
blogRepository.deleteAll();
blogRepository.save(new Blog("1", "好了歌", "世上皆知神仙好"));
blogRepository.save(new Blog("2", "功名利禄忘不了", "窗前明月光"));
blogRepository.save(new Blog("3", "疑似地上霜", "举头望明月"));
Pageable pageable = new PageRequest(0, 20);
Page<Blog> page = blogRepository.findByTitleLikeOrContentLike("好了歌","窗前", pageable);
assertThat(page.getTotalElements()).isEqualTo(2);
}
}
3. 向URL传参,返回查询结果。
@RestController
@RequestMapping("/blogs")
public class BlogController {
@Autowired
private BlogRepository blogRepository;
@GetMapping
public List<Blog> list(@RequestParam(value = "title", required = false, defaultValue = "") String title,
@RequestParam(value = "content", required = false, defaultValue = "") String content,
@RequestParam(value = "pageIndex", required = false, defaultValue = "0") int pageIndex,
@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {
// 数据在 Test 里面先初始化了,这里只管取数据
Pageable pageable = new PageRequest(pageIndex, pageSize);
Page<Blog> page = blogRepository.findByTitleLikeOrContentLike(title, content, pageable);
return page.getContent();
}
}